@ax-llm/ax 16.0.12 → 16.0.13
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/cli/index.mjs +3 -4
- package/index.cjs +23 -23
- package/index.cjs.map +1 -1
- package/index.global.js +21 -21
- package/index.global.js.map +1 -1
- package/index.js +23 -23
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/scripts/postinstall.mjs +4 -2
- package/skills/ax-llm.md +1 -1
package/index.global.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var ax=(()=>{var Yc=Object.create;var Pr=Object.defineProperty;var Qc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Zc=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty;var tu=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Er=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),nu=(i,e)=>{for(var t in e)Pr(i,t,{get:e[t],enumerable:!0})},zi=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xc(e))!eu.call(i,r)&&r!==t&&Pr(i,r,{get:()=>e[r],enumerable:!(n=Qc(e,r))||n.enumerable});return i};var Gn=(i,e,t)=>(t=i!=null?Yc(Zc(i)):{},zi(e||!i||!i.__esModule?Pr(t,"default",{value:i,enumerable:!0}):t,i)),ru=i=>zi(Pr({},"__esModule",{value:!0}),i);var Bl=Er((gi,hi)=>{"use strict";(function(i,e){typeof gi=="object"&&typeof hi<"u"?hi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs=e()})(gi,function(){"use strict";var i=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",s="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+)?$/,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"],I=R%100;return"["+R+(w[(I-20)%10]||w[I]||w[0])+"]"}},x=function(R,w,I){var _=String(R);return!_||_.length>=w?R:""+Array(w+1-_.length).join(I)+R},A={s:x,z:function(R){var w=-R.utcOffset(),I=Math.abs(w),_=Math.floor(I/60),k=I%60;return(w<=0?"+":"-")+x(_,2,"0")+":"+x(k,2,"0")},m:function R(w,I){if(w.date()<I.date())return-R(I,w);var _=12*(I.year()-w.year())+(I.month()-w.month()),k=w.clone().add(_,c),S=I-k<0,E=w.clone().add(_+(S?-1:1),c);return+(-(_+(I-k)/(S?k-E:E-k))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:c,y:p,w:l,d:a,D:d,h:s,m:o,s:r,ms:n,Q:u}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},T="en",y={};y[T]=f;var b="$isDayjsObject",C=function(R){return R instanceof M||!(!R||!R[b])},P=function R(w,I,_){var k;if(!w)return T;if(typeof w=="string"){var S=w.toLowerCase();y[S]&&(k=S),I&&(y[S]=I,k=S);var E=w.split("-");if(!k&&E.length>1)return R(E[0])}else{var $=w.name;y[$]=w,k=$}return!_&&k&&(T=k),k||!_&&T},O=function(R,w){if(C(R))return R.clone();var I=typeof w=="object"?w:{};return I.date=R,I.args=arguments,new M(I)},v=A;v.l=P,v.i=C,v.w=function(R,w){return O(R,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var M=function(){function R(I){this.$L=P(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[b]=!0}var w=R.prototype;return w.parse=function(I){this.$d=function(_){var k=_.date,S=_.utc;if(k===null)return new Date(NaN);if(v.u(k))return new Date;if(k instanceof Date)return new Date(k);if(typeof k=="string"&&!/Z$/i.test(k)){var E=k.match(g);if(E){var $=E[2]-1||0,N=(E[7]||"0").substring(0,3);return S?new Date(Date.UTC(E[1],$,E[3]||1,E[4]||0,E[5]||0,E[6]||0,N)):new Date(E[1],$,E[3]||1,E[4]||0,E[5]||0,E[6]||0,N)}}return new Date(k)}(I),this.init()},w.init=function(){var I=this.$d;this.$y=I.getFullYear(),this.$M=I.getMonth(),this.$D=I.getDate(),this.$W=I.getDay(),this.$H=I.getHours(),this.$m=I.getMinutes(),this.$s=I.getSeconds(),this.$ms=I.getMilliseconds()},w.$utils=function(){return v},w.isValid=function(){return this.$d.toString()!==m},w.isSame=function(I,_){var k=O(I);return this.startOf(_)<=k&&k<=this.endOf(_)},w.isAfter=function(I,_){return O(I)<this.startOf(_)},w.isBefore=function(I,_){return this.endOf(_)<O(I)},w.$g=function(I,_,k){return v.u(I)?this[_]:this.set(k,I)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(I,_){var k=this,S=!!v.u(_)||_,E=v.p(I),$=function(me,le){var oe=v.w(k.$u?Date.UTC(k.$y,le,me):new Date(k.$y,le,me),k);return S?oe:oe.endOf(a)},N=function(me,le){return v.w(k.toDate()[me].apply(k.toDate("s"),(S?[0,0,0,0]:[23,59,59,999]).slice(le)),k)},L=this.$W,U=this.$M,H=this.$D,W="set"+(this.$u?"UTC":"");switch(E){case p:return S?$(1,0):$(31,11);case c:return S?$(1,U):$(0,U+1);case l:var ue=this.$locale().weekStart||0,ae=(L<ue?L+7:L)-ue;return $(S?H-ae:H+(6-ae),U);case a:case d:return N(W+"Hours",0);case s:return N(W+"Minutes",1);case o:return N(W+"Seconds",2);case r:return N(W+"Milliseconds",3);default:return this.clone()}},w.endOf=function(I){return this.startOf(I,!1)},w.$set=function(I,_){var k,S=v.p(I),E="set"+(this.$u?"UTC":""),$=(k={},k[a]=E+"Date",k[d]=E+"Date",k[c]=E+"Month",k[p]=E+"FullYear",k[s]=E+"Hours",k[o]=E+"Minutes",k[r]=E+"Seconds",k[n]=E+"Milliseconds",k)[S],N=S===a?this.$D+(_-this.$W):_;if(S===c||S===p){var L=this.clone().set(d,1);L.$d[$](N),L.init(),this.$d=L.set(d,Math.min(this.$D,L.daysInMonth())).$d}else $&&this.$d[$](N);return this.init(),this},w.set=function(I,_){return this.clone().$set(I,_)},w.get=function(I){return this[v.p(I)]()},w.add=function(I,_){var k,S=this;I=Number(I);var E=v.p(_),$=function(U){var H=O(S);return v.w(H.date(H.date()+Math.round(U*I)),S)};if(E===c)return this.set(c,this.$M+I);if(E===p)return this.set(p,this.$y+I);if(E===a)return $(1);if(E===l)return $(7);var N=(k={},k[o]=e,k[s]=t,k[r]=i,k)[E]||1,L=this.$d.getTime()+I*N;return v.w(L,this)},w.subtract=function(I,_){return this.add(-1*I,_)},w.format=function(I){var _=this,k=this.$locale();if(!this.isValid())return k.invalidDate||m;var S=I||"YYYY-MM-DDTHH:mm:ssZ",E=v.z(this),$=this.$H,N=this.$m,L=this.$M,U=k.weekdays,H=k.months,W=k.meridiem,ue=function(le,oe,Re,ye){return le&&(le[oe]||le(_,S))||Re[oe].slice(0,ye)},ae=function(le){return v.s($%12||12,le,"0")},me=W||function(le,oe,Re){var ye=le<12?"AM":"PM";return Re?ye.toLowerCase():ye};return S.replace(h,function(le,oe){return oe||function(Re){switch(Re){case"YY":return String(_.$y).slice(-2);case"YYYY":return v.s(_.$y,4,"0");case"M":return L+1;case"MM":return v.s(L+1,2,"0");case"MMM":return ue(k.monthsShort,L,H,3);case"MMMM":return ue(H,L);case"D":return _.$D;case"DD":return v.s(_.$D,2,"0");case"d":return String(_.$W);case"dd":return ue(k.weekdaysMin,_.$W,U,2);case"ddd":return ue(k.weekdaysShort,_.$W,U,3);case"dddd":return U[_.$W];case"H":return String($);case"HH":return v.s($,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return me($,N,!0);case"A":return me($,N,!1);case"m":return String(N);case"mm":return v.s(N,2,"0");case"s":return String(_.$s);case"ss":return v.s(_.$s,2,"0");case"SSS":return v.s(_.$ms,3,"0");case"Z":return E}return null}(le)||E.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(I,_,k){var S,E=this,$=v.p(_),N=O(I),L=(N.utcOffset()-this.utcOffset())*e,U=this-N,H=function(){return v.m(E,N)};switch($){case p:S=H()/12;break;case c:S=H();break;case u:S=H()/3;break;case l:S=(U-L)/6048e5;break;case a:S=(U-L)/864e5;break;case s:S=U/t;break;case o:S=U/e;break;case r:S=U/i;break;default:S=U}return k?S:v.a(S)},w.daysInMonth=function(){return this.endOf(c).$D},w.$locale=function(){return y[this.$L]},w.locale=function(I,_){if(!I)return this.$L;var k=this.clone(),S=P(I,_,!0);return S&&(k.$L=S),k},w.clone=function(){return v.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}(),F=M.prototype;return O.prototype=F,[["$ms",n],["$s",r],["$m",o],["$H",s],["$W",a],["$M",c],["$y",p],["$D",d]].forEach(function(R){F[R[1]]=function(w){return this.$g(w,R[0],R[1])}}),O.extend=function(R,w){return R.$i||(R(w,M,O),R.$i=!0),O},O.locale=P,O.isDayjs=C,O.unix=function(R){return O(1e3*R)},O.en=y[T],O.Ls=y,O.p={},O})});var jl=Er((fi,xi)=>{"use strict";(function(i,e){typeof fi=="object"&&typeof xi<"u"?xi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_customParseFormat=e()})(fi,function(){"use strict";var i={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]+/,s={},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),x=60*f[1]+(+f[2]||0);return x===0?0:f[0]==="+"?-x:x}(g)}],u=function(g){var h=s[g];return h&&(h.indexOf?h:h.s.concat(h.f))},p=function(g,h){var f,x=s.meridiem;if(x){for(var A=1;A<=24;A+=1)if(g.indexOf(x(A,0,h))>-1){f=A>12;break}}else f=g===(h?"pm":"PM");return f},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 h=s.ordinal,f=g.match(/\d+/);if(this.day=f[0],h)for(var x=1;x<=31;x+=1)h(x).replace(/\[|\]/g,"")===g&&(this.day=x)}],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(x){return x.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=s&&s.formats;for(var x=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(O,v,M){var F=M&&M.toUpperCase();return v||f[M]||i[M]||f[F].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(R,w,I){return w||I.slice(1)})})).match(e),A=x.length,T=0;T<A;T+=1){var y=x[T],b=d[y],C=b&&b[0],P=b&&b[1];x[T]=P?{regex:C,parser:P}:y.replace(/^\[|\]$/g,"")}return function(O){for(var v={},M=0,F=0;M<A;M+=1){var R=x[M];if(typeof R=="string")F+=R.length;else{var w=R.regex,I=R.parser,_=O.slice(F),k=w.exec(_)[0];I.call(v,k),O=O.replace(k,"")}}return function(S){var E=S.afternoon;if(E!==void 0){var $=S.hours;E?$<12&&(S.hours+=12):$===12&&(S.hours=0),delete S.afternoon}}(v),v}}return function(g,h,f){f.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var x=h.prototype,A=x.parse;x.parse=function(T){var y=T.date,b=T.utc,C=T.args;this.$u=b;var P=C[1];if(typeof P=="string"){var O=C[2]===!0,v=C[3]===!0,M=O||v,F=C[2];v&&(F=C[2]),s=this.$locale(),!O&&F&&(s=f.Ls[F]),this.$d=function(_,k,S,E){try{if(["x","X"].indexOf(k)>-1)return new Date((k==="X"?1e3:1)*_);var $=m(k)(_),N=$.year,L=$.month,U=$.day,H=$.hours,W=$.minutes,ue=$.seconds,ae=$.milliseconds,me=$.zone,le=$.week,oe=new Date,Re=U||(N||L?1:oe.getDate()),ye=N||oe.getFullYear(),ze=0;N&&!L||(ze=L>0?L-1:oe.getMonth());var xe,ke=H||0,V=W||0,ne=ue||0,B=ae||0;return me?new Date(Date.UTC(ye,ze,Re,ke,V,ne,B+60*me.offset*1e3)):S?new Date(Date.UTC(ye,ze,Re,ke,V,ne,B)):(xe=new Date(ye,ze,Re,ke,V,ne,B),le&&(xe=E(xe).week(le).toDate()),xe)}catch{return new Date("")}}(y,P,b,f),this.init(),F&&F!==!0&&(this.$L=this.locale(F).$L),M&&y!=this.format(P)&&(this.$d=new Date("")),s={}}else if(P instanceof Array)for(var R=P.length,w=1;w<=R;w+=1){C[1]=P[w-1];var I=f.apply(this,C);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}w===R&&(this.$d=new Date(""))}else A.call(this,T)}}})});var ql=Er((Ai,yi)=>{"use strict";(function(i,e){typeof Ai=="object"&&typeof yi<"u"?yi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_timezone=e()})(Ai,function(){"use strict";var i={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var o,s=function(u,p,d){d===void 0&&(d={});var m=new Date(u),g=function(h,f){f===void 0&&(f={});var x=f.timeZoneName||"short",A=h+"|"+x,T=e[A];return T||(T=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:x}),e[A]=T),T}(p,d);return g.formatToParts(m)},a=function(u,p){for(var d=s(u,p),m=[],g=0;g<d.length;g+=1){var h=d[g],f=h.type,x=h.value,A=i[f];A>=0&&(m[A]=parseInt(x,10))}var T=m[3],y=T===24?0:T,b=m[0]+"-"+m[1]+"-"+m[2]+" "+y+":"+m[4]+":"+m[5]+":000",C=+u;return(r.utc(b).valueOf()-(C-=C%1e3))/6e4},l=n.prototype;l.tz=function(u,p){u===void 0&&(u=o);var d,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:u}),f=Math.round((g-new Date(h))/1e3/60),x=15*-Math.round(g.getTimezoneOffset()/15)-f;if(!Number(x))d=this.utcOffset(0,p);else if(d=r(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(x,!0),p){var A=d.utcOffset();d=d.add(m-A,"minute")}return d.$x.$timezone=u,d},l.offsetName=function(u){var p=this.$x.$timezone||r.tz.guess(),d=s(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,h=a(+r(),g);if(typeof u!="string")return r(u).tz(g);var f=function(y,b,C){var P=y-60*b*1e3,O=a(P,C);if(b===O)return[P,b];var v=a(P-=60*(O-b)*1e3,C);return O===v?[P,O]:[y-60*Math.min(O,v)*1e3,Math.max(O,v)]}(r.utc(u,m).valueOf(),h,g),x=f[0],A=f[1],T=r(x).utcOffset(A);return T.$x.$timezone=g,T},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var zl=Er((bi,Ii)=>{"use strict";(function(i,e){typeof bi=="object"&&typeof Ii<"u"?Ii.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_utc=e()})(bi,function(){"use strict";var i="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var s=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},s.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),i):g},s.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=s.parse;s.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=s.init;s.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=s.utcOffset;s.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(T){T===void 0&&(T="");var y=T.match(e);if(!y)return null;var b=(""+y[0]).match(t)||["-",0,0],C=b[0],P=60*+b[1]+ +b[2];return P===0?0:C==="+"?P:-P}(m),m===null))return this;var f=Math.abs(m)<=16?60*m:m,x=this;if(g)return x.$offset=f,x.$u=m===0,x;if(m!==0){var A=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(x=this.local().add(f+A,i)).$offset=f,x.$x.$localOffset=A}else x=this.utc();return x};var u=s.format;s.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,g)},s.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},s.isUTC=function(){return!!this.$u},s.toISOString=function(){return this.toDate().toISOString()},s.toString=function(){return this.toDate().toUTCString()};var p=s.toDate;s.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():p.call(this)};var d=s.diff;s.diff=function(m,g,h){if(m&&this.$u===m.$u)return d.call(this,m,g,h);var f=this.local(),x=o(m).local();return d.call(f,x,g,h)}}})});var od={};nu(od,{AxACE:()=>ns,AxACEOptimizedProgram:()=>Rr,AxAI:()=>cr,AxAIAnthropic:()=>Jt,AxAIAnthropicModel:()=>Vn,AxAIAnthropicVertexModel:()=>Wn,AxAIAzureOpenAI:()=>en,AxAICohere:()=>tn,AxAICohereEmbedModel:()=>Xn,AxAICohereModel:()=>Qn,AxAIDeepSeek:()=>nn,AxAIDeepSeekModel:()=>Zn,AxAIGoogleGemini:()=>rn,AxAIGoogleGeminiEmbedModel:()=>eo,AxAIGoogleGeminiEmbedTypes:()=>zs,AxAIGoogleGeminiModel:()=>er,AxAIGoogleGeminiSafetyCategory:()=>to,AxAIGoogleGeminiSafetyThreshold:()=>no,AxAIGrok:()=>fn,AxAIGrokEmbedModels:()=>ri,AxAIGrokModel:()=>lr,AxAIGroq:()=>sn,AxAIGroqModel:()=>tr,AxAIHuggingFace:()=>an,AxAIHuggingFaceModel:()=>ao,AxAIMistral:()=>ln,AxAIMistralEmbedModels:()=>Js,AxAIMistralModel:()=>nr,AxAIOllama:()=>cn,AxAIOpenAI:()=>Zt,AxAIOpenAIBase:()=>Te,AxAIOpenAIEmbedModel:()=>Yt,AxAIOpenAIModel:()=>Yn,AxAIOpenAIResponses:()=>pn,AxAIOpenAIResponsesBase:()=>rr,AxAIOpenAIResponsesImpl:()=>un,AxAIOpenAIResponsesModel:()=>Qt,AxAIOpenRouter:()=>dn,AxAIRefusalError:()=>Ae,AxAIReka:()=>mn,AxAIRekaModel:()=>sr,AxAIServiceAbortedError:()=>qt,AxAIServiceAuthenticationError:()=>yt,AxAIServiceError:()=>Fe,AxAIServiceNetworkError:()=>Ge,AxAIServiceResponseError:()=>At,AxAIServiceStatusError:()=>We,AxAIServiceStreamTerminatedError:()=>Qe,AxAIServiceTimeoutError:()=>st,AxAITogether:()=>gn,AxAIWebLLM:()=>hn,AxAIWebLLMModel:()=>ar,AxAgent:()=>Or,AxApacheTika:()=>Ko,AxAssertionError:()=>dt,AxBalancer:()=>Jr,AxBaseAI:()=>we,AxBaseOptimizer:()=>qe,AxBootstrapFewShot:()=>Mn,AxContentProcessingError:()=>it,AxDB:()=>Io,AxDBBase:()=>Ze,AxDBCloudflare:()=>xn,AxDBManager:()=>To,AxDBMemory:()=>kt,AxDBPinecone:()=>An,AxDBWeaviate:()=>yn,AxDefaultCostTracker:()=>br,AxDefaultResultReranker:()=>Ho,AxDockerSession:()=>ls,AxEmbeddingAdapter:()=>cs,AxEvalUtil:()=>yc,AxFlow:()=>vr,AxFlowDependencyAnalyzer:()=>Pn,AxFlowExecutionPlanner:()=>Fn,AxFlowSubContextImpl:()=>Nn,AxFlowTypedSubContextImpl:()=>is,AxFluentFieldType:()=>Oe,AxFunctionError:()=>dr,AxFunctionProcessor:()=>gr,AxGEPA:()=>On,AxGEPAFlow:()=>rs,AxGen:()=>Ce,AxGenerateError:()=>Ar,AxHFDataLoader:()=>ts,AxInstanceRegistry:()=>Cn,AxJudge:()=>vn,AxLLMRequestTypeValues:()=>Ss,AxLearn:()=>es,AxMCPClient:()=>us,AxMCPHTTPSSETransport:()=>ms,AxMCPStreambleHTTPTransport:()=>ds,AxMediaNotSupportedError:()=>Xe,AxMemory:()=>bn,AxMiPRO:()=>ss,AxMockAIService:()=>uo,AxMultiServiceRouter:()=>po,AxOptimizedProgramImpl:()=>gt,AxProgram:()=>Et,AxPromptTemplate:()=>Gt,AxProviderRouter:()=>fo,AxRateLimiterTokenUsage:()=>on,AxSignature:()=>be,AxSignatureBuilder:()=>fr,AxSimpleClassifier:()=>Wo,AxSimpleClassifierClass:()=>Vo,AxSpanKindValues:()=>Os,AxStopFunctionCallException:()=>Dt,AxStringUtil:()=>zo,AxSynth:()=>kn,AxTestPrompt:()=>Jo,AxTokenLimitError:()=>Un,AxTraceLogger:()=>Sn,agent:()=>qc,ai:()=>xl,ax:()=>$e,axAIAnthropicDefaultConfig:()=>Ds,axAIAnthropicVertexDefaultConfig:()=>Ha,axAIAzureOpenAIBestConfig:()=>Ja,axAIAzureOpenAICreativeConfig:()=>Va,axAIAzureOpenAIDefaultConfig:()=>Gs,axAIAzureOpenAIFastConfig:()=>Wa,axAICohereCreativeConfig:()=>el,axAICohereDefaultConfig:()=>js,axAIDeepSeekCodeConfig:()=>tl,axAIDeepSeekDefaultConfig:()=>qs,axAIGoogleGeminiDefaultConfig:()=>Ks,axAIGoogleGeminiDefaultCreativeConfig:()=>ol,axAIGrokBestConfig:()=>fl,axAIGrokDefaultConfig:()=>bo,axAIHuggingFaceCreativeConfig:()=>sl,axAIHuggingFaceDefaultConfig:()=>Ws,axAIMistralBestConfig:()=>il,axAIMistralDefaultConfig:()=>co,axAIOllamaDefaultConfig:()=>Ys,axAIOllamaDefaultCreativeConfig:()=>al,axAIOpenAIBestConfig:()=>Kr,axAIOpenAICreativeConfig:()=>Vr,axAIOpenAIDefaultConfig:()=>$t,axAIOpenAIFastConfig:()=>Wr,axAIOpenAIResponsesBestConfig:()=>ll,axAIOpenAIResponsesCreativeConfig:()=>cl,axAIOpenAIResponsesDefaultConfig:()=>or,axAIOpenRouterDefaultConfig:()=>Xs,axAIRekaBestConfig:()=>dl,axAIRekaCreativeConfig:()=>ml,axAIRekaDefaultConfig:()=>ir,axAIRekaFastConfig:()=>gl,axAITogetherDefaultConfig:()=>ei,axAIWebLLMCreativeConfig:()=>hl,axAIWebLLMDefaultConfig:()=>ni,axAnalyzeChatPromptRequirements:()=>ul,axAnalyzeRequestRequirements:()=>Nt,axBaseAIDefaultConfig:()=>ie,axBaseAIDefaultCreativeConfig:()=>Se,axCheckMetricsHealth:()=>Al,axCreateDefaultColorLogger:()=>vs,axCreateDefaultOptimizerColorLogger:()=>Ni,axCreateDefaultOptimizerTextLogger:()=>Tc,axCreateDefaultTextLogger:()=>ga,axCreateFlowColorLogger:()=>wr,axCreateFlowTextLogger:()=>Mc,axDefaultFlowLogger:()=>Pc,axDefaultMetricsConfig:()=>ai,axDefaultOptimizerLogger:()=>yr,axDefaultOptimizerMetricsConfig:()=>Di,axGetCompatibilityReport:()=>Ya,axGetFormatCompatibility:()=>Xa,axGetMetricsConfig:()=>bl,axGetOptimizerMetricsConfig:()=>Rc,axGetProvidersWithMediaSupport:()=>Qa,axGlobals:()=>X,axModelInfoAnthropic:()=>Jn,axModelInfoCohere:()=>Xr,axModelInfoDeepSeek:()=>Zr,axModelInfoGoogleGemini:()=>ro,axModelInfoGrok:()=>yo,axModelInfoGroq:()=>so,axModelInfoHuggingFace:()=>io,axModelInfoMistral:()=>lo,axModelInfoOpenAI:()=>Xt,axModelInfoOpenAIResponses:()=>Hr,axModelInfoReka:()=>ho,axModelInfoTogether:()=>xo,axModelInfoWebLLM:()=>Ao,axProcessContentForProvider:()=>go,axRAG:()=>zc,axScoreProvidersForRequest:()=>Yr,axSelectOptimalProvider:()=>Qr,axSpanAttributes:()=>Q,axSpanEvents:()=>at,axUpdateMetricsConfig:()=>yl,axUpdateOptimizerMetricsConfig:()=>Cc,axValidateChatRequestMessage:()=>Wt,axValidateChatResponseResult:()=>zr,axValidateProviderCapabilities:()=>Us,f:()=>de,flow:()=>as,s:()=>wc});function Ye({model:i,modelInfo:e,models:t}){let n=t?.find(c=>c.key===i),r=n&&"model"in n?n.model:i,o=e.find(c=>c.name===i);if(o)return o;let s=e.find(c=>c.name===r);if(s)return s;let a=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+$/,""),l=e.find(c=>c.name===a);return l||null}var fs=(()=>{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 Ee(){return fs.randomUUID()}async function ou(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await fs.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var hs=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 s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return ou(this.data)}};function Le(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new hs}function Hi(){return fs}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 Yc=Object.create;var Pr=Object.defineProperty;var Qc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Zc=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty;var tu=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var Er=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),nu=(i,e)=>{for(var t in e)Pr(i,t,{get:e[t],enumerable:!0})},zi=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xc(e))!eu.call(i,r)&&r!==t&&Pr(i,r,{get:()=>e[r],enumerable:!(n=Qc(e,r))||n.enumerable});return i};var Gn=(i,e,t)=>(t=i!=null?Yc(Zc(i)):{},zi(e||!i||!i.__esModule?Pr(t,"default",{value:i,enumerable:!0}):t,i)),ru=i=>zi(Pr({},"__esModule",{value:!0}),i);var Bl=Er((gi,hi)=>{"use strict";(function(i,e){typeof gi=="object"&&typeof hi<"u"?hi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs=e()})(gi,function(){"use strict";var i=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",s="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+)?$/,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"],I=R%100;return"["+R+(w[(I-20)%10]||w[I]||w[0])+"]"}},x=function(R,w,I){var _=String(R);return!_||_.length>=w?R:""+Array(w+1-_.length).join(I)+R},A={s:x,z:function(R){var w=-R.utcOffset(),I=Math.abs(w),_=Math.floor(I/60),M=I%60;return(w<=0?"+":"-")+x(_,2,"0")+":"+x(M,2,"0")},m:function R(w,I){if(w.date()<I.date())return-R(I,w);var _=12*(I.year()-w.year())+(I.month()-w.month()),M=w.clone().add(_,c),O=I-M<0,E=w.clone().add(_+(O?-1:1),c);return+(-(_+(I-M)/(O?M-E:E-M))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:c,y:p,w:l,d:a,D:d,h:s,m:o,s:r,ms:n,Q:u}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},T="en",y={};y[T]=f;var b="$isDayjsObject",C=function(R){return R instanceof k||!(!R||!R[b])},P=function R(w,I,_){var M;if(!w)return T;if(typeof w=="string"){var O=w.toLowerCase();y[O]&&(M=O),I&&(y[O]=I,M=O);var E=w.split("-");if(!M&&E.length>1)return R(E[0])}else{var $=w.name;y[$]=w,M=$}return!_&&M&&(T=M),M||!_&&T},S=function(R,w){if(C(R))return R.clone();var I=typeof w=="object"?w:{};return I.date=R,I.args=arguments,new k(I)},v=A;v.l=P,v.i=C,v.w=function(R,w){return S(R,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var k=function(){function R(I){this.$L=P(I.locale,null,!0),this.parse(I),this.$x=this.$x||I.x||{},this[b]=!0}var w=R.prototype;return w.parse=function(I){this.$d=function(_){var M=_.date,O=_.utc;if(M===null)return new Date(NaN);if(v.u(M))return new Date;if(M instanceof Date)return new Date(M);if(typeof M=="string"&&!/Z$/i.test(M)){var E=M.match(g);if(E){var $=E[2]-1||0,N=(E[7]||"0").substring(0,3);return O?new Date(Date.UTC(E[1],$,E[3]||1,E[4]||0,E[5]||0,E[6]||0,N)):new Date(E[1],$,E[3]||1,E[4]||0,E[5]||0,E[6]||0,N)}}return new Date(M)}(I),this.init()},w.init=function(){var I=this.$d;this.$y=I.getFullYear(),this.$M=I.getMonth(),this.$D=I.getDate(),this.$W=I.getDay(),this.$H=I.getHours(),this.$m=I.getMinutes(),this.$s=I.getSeconds(),this.$ms=I.getMilliseconds()},w.$utils=function(){return v},w.isValid=function(){return this.$d.toString()!==m},w.isSame=function(I,_){var M=S(I);return this.startOf(_)<=M&&M<=this.endOf(_)},w.isAfter=function(I,_){return S(I)<this.startOf(_)},w.isBefore=function(I,_){return this.endOf(_)<S(I)},w.$g=function(I,_,M){return v.u(I)?this[_]:this.set(M,I)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(I,_){var M=this,O=!!v.u(_)||_,E=v.p(I),$=function(me,le){var oe=v.w(M.$u?Date.UTC(M.$y,le,me):new Date(M.$y,le,me),M);return O?oe:oe.endOf(a)},N=function(me,le){return v.w(M.toDate()[me].apply(M.toDate("s"),(O?[0,0,0,0]:[23,59,59,999]).slice(le)),M)},L=this.$W,U=this.$M,H=this.$D,W="set"+(this.$u?"UTC":"");switch(E){case p:return O?$(1,0):$(31,11);case c:return O?$(1,U):$(0,U+1);case l:var ue=this.$locale().weekStart||0,ae=(L<ue?L+7:L)-ue;return $(O?H-ae:H+(6-ae),U);case a:case d:return N(W+"Hours",0);case s:return N(W+"Minutes",1);case o:return N(W+"Seconds",2);case r:return N(W+"Milliseconds",3);default:return this.clone()}},w.endOf=function(I){return this.startOf(I,!1)},w.$set=function(I,_){var M,O=v.p(I),E="set"+(this.$u?"UTC":""),$=(M={},M[a]=E+"Date",M[d]=E+"Date",M[c]=E+"Month",M[p]=E+"FullYear",M[s]=E+"Hours",M[o]=E+"Minutes",M[r]=E+"Seconds",M[n]=E+"Milliseconds",M)[O],N=O===a?this.$D+(_-this.$W):_;if(O===c||O===p){var L=this.clone().set(d,1);L.$d[$](N),L.init(),this.$d=L.set(d,Math.min(this.$D,L.daysInMonth())).$d}else $&&this.$d[$](N);return this.init(),this},w.set=function(I,_){return this.clone().$set(I,_)},w.get=function(I){return this[v.p(I)]()},w.add=function(I,_){var M,O=this;I=Number(I);var E=v.p(_),$=function(U){var H=S(O);return v.w(H.date(H.date()+Math.round(U*I)),O)};if(E===c)return this.set(c,this.$M+I);if(E===p)return this.set(p,this.$y+I);if(E===a)return $(1);if(E===l)return $(7);var N=(M={},M[o]=e,M[s]=t,M[r]=i,M)[E]||1,L=this.$d.getTime()+I*N;return v.w(L,this)},w.subtract=function(I,_){return this.add(-1*I,_)},w.format=function(I){var _=this,M=this.$locale();if(!this.isValid())return M.invalidDate||m;var O=I||"YYYY-MM-DDTHH:mm:ssZ",E=v.z(this),$=this.$H,N=this.$m,L=this.$M,U=M.weekdays,H=M.months,W=M.meridiem,ue=function(le,oe,Re,ye){return le&&(le[oe]||le(_,O))||Re[oe].slice(0,ye)},ae=function(le){return v.s($%12||12,le,"0")},me=W||function(le,oe,Re){var ye=le<12?"AM":"PM";return Re?ye.toLowerCase():ye};return O.replace(h,function(le,oe){return oe||function(Re){switch(Re){case"YY":return String(_.$y).slice(-2);case"YYYY":return v.s(_.$y,4,"0");case"M":return L+1;case"MM":return v.s(L+1,2,"0");case"MMM":return ue(M.monthsShort,L,H,3);case"MMMM":return ue(H,L);case"D":return _.$D;case"DD":return v.s(_.$D,2,"0");case"d":return String(_.$W);case"dd":return ue(M.weekdaysMin,_.$W,U,2);case"ddd":return ue(M.weekdaysShort,_.$W,U,3);case"dddd":return U[_.$W];case"H":return String($);case"HH":return v.s($,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return me($,N,!0);case"A":return me($,N,!1);case"m":return String(N);case"mm":return v.s(N,2,"0");case"s":return String(_.$s);case"ss":return v.s(_.$s,2,"0");case"SSS":return v.s(_.$ms,3,"0");case"Z":return E}return null}(le)||E.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(I,_,M){var O,E=this,$=v.p(_),N=S(I),L=(N.utcOffset()-this.utcOffset())*e,U=this-N,H=function(){return v.m(E,N)};switch($){case p:O=H()/12;break;case c:O=H();break;case u:O=H()/3;break;case l:O=(U-L)/6048e5;break;case a:O=(U-L)/864e5;break;case s:O=U/t;break;case o:O=U/e;break;case r:O=U/i;break;default:O=U}return M?O:v.a(O)},w.daysInMonth=function(){return this.endOf(c).$D},w.$locale=function(){return y[this.$L]},w.locale=function(I,_){if(!I)return this.$L;var M=this.clone(),O=P(I,_,!0);return O&&(M.$L=O),M},w.clone=function(){return v.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}(),F=k.prototype;return S.prototype=F,[["$ms",n],["$s",r],["$m",o],["$H",s],["$W",a],["$M",c],["$y",p],["$D",d]].forEach(function(R){F[R[1]]=function(w){return this.$g(w,R[0],R[1])}}),S.extend=function(R,w){return R.$i||(R(w,k,S),R.$i=!0),S},S.locale=P,S.isDayjs=C,S.unix=function(R){return S(1e3*R)},S.en=y[T],S.Ls=y,S.p={},S})});var jl=Er((fi,xi)=>{"use strict";(function(i,e){typeof fi=="object"&&typeof xi<"u"?xi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_customParseFormat=e()})(fi,function(){"use strict";var i={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]+/,s={},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),x=60*f[1]+(+f[2]||0);return x===0?0:f[0]==="+"?-x:x}(g)}],u=function(g){var h=s[g];return h&&(h.indexOf?h:h.s.concat(h.f))},p=function(g,h){var f,x=s.meridiem;if(x){for(var A=1;A<=24;A+=1)if(g.indexOf(x(A,0,h))>-1){f=A>12;break}}else f=g===(h?"pm":"PM");return f},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 h=s.ordinal,f=g.match(/\d+/);if(this.day=f[0],h)for(var x=1;x<=31;x+=1)h(x).replace(/\[|\]/g,"")===g&&(this.day=x)}],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(x){return x.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=s&&s.formats;for(var x=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(S,v,k){var F=k&&k.toUpperCase();return v||f[k]||i[k]||f[F].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(R,w,I){return w||I.slice(1)})})).match(e),A=x.length,T=0;T<A;T+=1){var y=x[T],b=d[y],C=b&&b[0],P=b&&b[1];x[T]=P?{regex:C,parser:P}:y.replace(/^\[|\]$/g,"")}return function(S){for(var v={},k=0,F=0;k<A;k+=1){var R=x[k];if(typeof R=="string")F+=R.length;else{var w=R.regex,I=R.parser,_=S.slice(F),M=w.exec(_)[0];I.call(v,M),S=S.replace(M,"")}}return function(O){var E=O.afternoon;if(E!==void 0){var $=O.hours;E?$<12&&(O.hours+=12):$===12&&(O.hours=0),delete O.afternoon}}(v),v}}return function(g,h,f){f.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var x=h.prototype,A=x.parse;x.parse=function(T){var y=T.date,b=T.utc,C=T.args;this.$u=b;var P=C[1];if(typeof P=="string"){var S=C[2]===!0,v=C[3]===!0,k=S||v,F=C[2];v&&(F=C[2]),s=this.$locale(),!S&&F&&(s=f.Ls[F]),this.$d=function(_,M,O,E){try{if(["x","X"].indexOf(M)>-1)return new Date((M==="X"?1e3:1)*_);var $=m(M)(_),N=$.year,L=$.month,U=$.day,H=$.hours,W=$.minutes,ue=$.seconds,ae=$.milliseconds,me=$.zone,le=$.week,oe=new Date,Re=U||(N||L?1:oe.getDate()),ye=N||oe.getFullYear(),ze=0;N&&!L||(ze=L>0?L-1:oe.getMonth());var xe,ke=H||0,V=W||0,ne=ue||0,B=ae||0;return me?new Date(Date.UTC(ye,ze,Re,ke,V,ne,B+60*me.offset*1e3)):O?new Date(Date.UTC(ye,ze,Re,ke,V,ne,B)):(xe=new Date(ye,ze,Re,ke,V,ne,B),le&&(xe=E(xe).week(le).toDate()),xe)}catch{return new Date("")}}(y,P,b,f),this.init(),F&&F!==!0&&(this.$L=this.locale(F).$L),k&&y!=this.format(P)&&(this.$d=new Date("")),s={}}else if(P instanceof Array)for(var R=P.length,w=1;w<=R;w+=1){C[1]=P[w-1];var I=f.apply(this,C);if(I.isValid()){this.$d=I.$d,this.$L=I.$L,this.init();break}w===R&&(this.$d=new Date(""))}else A.call(this,T)}}})});var ql=Er((Ai,yi)=>{"use strict";(function(i,e){typeof Ai=="object"&&typeof yi<"u"?yi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_timezone=e()})(Ai,function(){"use strict";var i={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var o,s=function(u,p,d){d===void 0&&(d={});var m=new Date(u),g=function(h,f){f===void 0&&(f={});var x=f.timeZoneName||"short",A=h+"|"+x,T=e[A];return T||(T=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:x}),e[A]=T),T}(p,d);return g.formatToParts(m)},a=function(u,p){for(var d=s(u,p),m=[],g=0;g<d.length;g+=1){var h=d[g],f=h.type,x=h.value,A=i[f];A>=0&&(m[A]=parseInt(x,10))}var T=m[3],y=T===24?0:T,b=m[0]+"-"+m[1]+"-"+m[2]+" "+y+":"+m[4]+":"+m[5]+":000",C=+u;return(r.utc(b).valueOf()-(C-=C%1e3))/6e4},l=n.prototype;l.tz=function(u,p){u===void 0&&(u=o);var d,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:u}),f=Math.round((g-new Date(h))/1e3/60),x=15*-Math.round(g.getTimezoneOffset()/15)-f;if(!Number(x))d=this.utcOffset(0,p);else if(d=r(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(x,!0),p){var A=d.utcOffset();d=d.add(m-A,"minute")}return d.$x.$timezone=u,d},l.offsetName=function(u){var p=this.$x.$timezone||r.tz.guess(),d=s(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,h=a(+r(),g);if(typeof u!="string")return r(u).tz(g);var f=function(y,b,C){var P=y-60*b*1e3,S=a(P,C);if(b===S)return[P,b];var v=a(P-=60*(S-b)*1e3,C);return S===v?[P,S]:[y-60*Math.min(S,v)*1e3,Math.max(S,v)]}(r.utc(u,m).valueOf(),h,g),x=f[0],A=f[1],T=r(x).utcOffset(A);return T.$x.$timezone=g,T},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(u){o=u}}})});var zl=Er((bi,Ii)=>{"use strict";(function(i,e){typeof bi=="object"&&typeof Ii<"u"?Ii.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_utc=e()})(bi,function(){"use strict";var i="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var s=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},s.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),i):g},s.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=s.parse;s.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=s.init;s.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=s.utcOffset;s.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(T){T===void 0&&(T="");var y=T.match(e);if(!y)return null;var b=(""+y[0]).match(t)||["-",0,0],C=b[0],P=60*+b[1]+ +b[2];return P===0?0:C==="+"?P:-P}(m),m===null))return this;var f=Math.abs(m)<=16?60*m:m,x=this;if(g)return x.$offset=f,x.$u=m===0,x;if(m!==0){var A=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(x=this.local().add(f+A,i)).$offset=f,x.$x.$localOffset=A}else x=this.utc();return x};var u=s.format;s.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return u.call(this,g)},s.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},s.isUTC=function(){return!!this.$u},s.toISOString=function(){return this.toDate().toISOString()},s.toString=function(){return this.toDate().toUTCString()};var p=s.toDate;s.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():p.call(this)};var d=s.diff;s.diff=function(m,g,h){if(m&&this.$u===m.$u)return d.call(this,m,g,h);var f=this.local(),x=o(m).local();return d.call(f,x,g,h)}}})});var od={};nu(od,{AxACE:()=>ns,AxACEOptimizedProgram:()=>Rr,AxAI:()=>cr,AxAIAnthropic:()=>Jt,AxAIAnthropicModel:()=>Vn,AxAIAnthropicVertexModel:()=>Wn,AxAIAzureOpenAI:()=>en,AxAICohere:()=>tn,AxAICohereEmbedModel:()=>Xn,AxAICohereModel:()=>Qn,AxAIDeepSeek:()=>nn,AxAIDeepSeekModel:()=>Zn,AxAIGoogleGemini:()=>rn,AxAIGoogleGeminiEmbedModel:()=>eo,AxAIGoogleGeminiEmbedTypes:()=>zs,AxAIGoogleGeminiModel:()=>er,AxAIGoogleGeminiSafetyCategory:()=>to,AxAIGoogleGeminiSafetyThreshold:()=>no,AxAIGrok:()=>fn,AxAIGrokEmbedModels:()=>ri,AxAIGrokModel:()=>lr,AxAIGroq:()=>sn,AxAIGroqModel:()=>tr,AxAIHuggingFace:()=>an,AxAIHuggingFaceModel:()=>ao,AxAIMistral:()=>ln,AxAIMistralEmbedModels:()=>Js,AxAIMistralModel:()=>nr,AxAIOllama:()=>cn,AxAIOpenAI:()=>Zt,AxAIOpenAIBase:()=>Te,AxAIOpenAIEmbedModel:()=>Yt,AxAIOpenAIModel:()=>Yn,AxAIOpenAIResponses:()=>pn,AxAIOpenAIResponsesBase:()=>rr,AxAIOpenAIResponsesImpl:()=>un,AxAIOpenAIResponsesModel:()=>Qt,AxAIOpenRouter:()=>dn,AxAIRefusalError:()=>Ae,AxAIReka:()=>mn,AxAIRekaModel:()=>sr,AxAIServiceAbortedError:()=>qt,AxAIServiceAuthenticationError:()=>yt,AxAIServiceError:()=>Fe,AxAIServiceNetworkError:()=>Ge,AxAIServiceResponseError:()=>At,AxAIServiceStatusError:()=>We,AxAIServiceStreamTerminatedError:()=>Qe,AxAIServiceTimeoutError:()=>st,AxAITogether:()=>gn,AxAIWebLLM:()=>hn,AxAIWebLLMModel:()=>ar,AxAgent:()=>Or,AxApacheTika:()=>Ko,AxAssertionError:()=>dt,AxBalancer:()=>Jr,AxBaseAI:()=>we,AxBaseOptimizer:()=>qe,AxBootstrapFewShot:()=>Mn,AxContentProcessingError:()=>it,AxDB:()=>Io,AxDBBase:()=>Ze,AxDBCloudflare:()=>xn,AxDBManager:()=>To,AxDBMemory:()=>kt,AxDBPinecone:()=>An,AxDBWeaviate:()=>yn,AxDefaultCostTracker:()=>br,AxDefaultResultReranker:()=>Ho,AxDockerSession:()=>ls,AxEmbeddingAdapter:()=>cs,AxEvalUtil:()=>yc,AxFlow:()=>vr,AxFlowDependencyAnalyzer:()=>Pn,AxFlowExecutionPlanner:()=>Fn,AxFlowSubContextImpl:()=>Nn,AxFlowTypedSubContextImpl:()=>is,AxFluentFieldType:()=>Oe,AxFunctionError:()=>dr,AxFunctionProcessor:()=>gr,AxGEPA:()=>On,AxGEPAFlow:()=>rs,AxGen:()=>Ce,AxGenerateError:()=>Ar,AxHFDataLoader:()=>ts,AxInstanceRegistry:()=>Cn,AxJudge:()=>vn,AxLLMRequestTypeValues:()=>Ss,AxLearn:()=>es,AxMCPClient:()=>us,AxMCPHTTPSSETransport:()=>ms,AxMCPStreambleHTTPTransport:()=>ds,AxMediaNotSupportedError:()=>Xe,AxMemory:()=>bn,AxMiPRO:()=>ss,AxMockAIService:()=>uo,AxMultiServiceRouter:()=>po,AxOptimizedProgramImpl:()=>gt,AxProgram:()=>Et,AxPromptTemplate:()=>Gt,AxProviderRouter:()=>fo,AxRateLimiterTokenUsage:()=>on,AxSignature:()=>be,AxSignatureBuilder:()=>fr,AxSimpleClassifier:()=>Wo,AxSimpleClassifierClass:()=>Vo,AxSpanKindValues:()=>Os,AxStopFunctionCallException:()=>Dt,AxStringUtil:()=>zo,AxSynth:()=>kn,AxTestPrompt:()=>Jo,AxTokenLimitError:()=>Un,AxTraceLogger:()=>Sn,agent:()=>qc,ai:()=>xl,ax:()=>$e,axAIAnthropicDefaultConfig:()=>Ds,axAIAnthropicVertexDefaultConfig:()=>Ha,axAIAzureOpenAIBestConfig:()=>Ja,axAIAzureOpenAICreativeConfig:()=>Va,axAIAzureOpenAIDefaultConfig:()=>Gs,axAIAzureOpenAIFastConfig:()=>Wa,axAICohereCreativeConfig:()=>el,axAICohereDefaultConfig:()=>js,axAIDeepSeekCodeConfig:()=>tl,axAIDeepSeekDefaultConfig:()=>qs,axAIGoogleGeminiDefaultConfig:()=>Ks,axAIGoogleGeminiDefaultCreativeConfig:()=>ol,axAIGrokBestConfig:()=>fl,axAIGrokDefaultConfig:()=>bo,axAIHuggingFaceCreativeConfig:()=>sl,axAIHuggingFaceDefaultConfig:()=>Ws,axAIMistralBestConfig:()=>il,axAIMistralDefaultConfig:()=>co,axAIOllamaDefaultConfig:()=>Ys,axAIOllamaDefaultCreativeConfig:()=>al,axAIOpenAIBestConfig:()=>Kr,axAIOpenAICreativeConfig:()=>Vr,axAIOpenAIDefaultConfig:()=>$t,axAIOpenAIFastConfig:()=>Wr,axAIOpenAIResponsesBestConfig:()=>ll,axAIOpenAIResponsesCreativeConfig:()=>cl,axAIOpenAIResponsesDefaultConfig:()=>or,axAIOpenRouterDefaultConfig:()=>Xs,axAIRekaBestConfig:()=>dl,axAIRekaCreativeConfig:()=>ml,axAIRekaDefaultConfig:()=>ir,axAIRekaFastConfig:()=>gl,axAITogetherDefaultConfig:()=>ei,axAIWebLLMCreativeConfig:()=>hl,axAIWebLLMDefaultConfig:()=>ni,axAnalyzeChatPromptRequirements:()=>ul,axAnalyzeRequestRequirements:()=>Nt,axBaseAIDefaultConfig:()=>ie,axBaseAIDefaultCreativeConfig:()=>Se,axCheckMetricsHealth:()=>Al,axCreateDefaultColorLogger:()=>vs,axCreateDefaultOptimizerColorLogger:()=>Ni,axCreateDefaultOptimizerTextLogger:()=>Tc,axCreateDefaultTextLogger:()=>ga,axCreateFlowColorLogger:()=>wr,axCreateFlowTextLogger:()=>Mc,axDefaultFlowLogger:()=>Pc,axDefaultMetricsConfig:()=>ai,axDefaultOptimizerLogger:()=>yr,axDefaultOptimizerMetricsConfig:()=>Di,axGetCompatibilityReport:()=>Ya,axGetFormatCompatibility:()=>Xa,axGetMetricsConfig:()=>bl,axGetOptimizerMetricsConfig:()=>Rc,axGetProvidersWithMediaSupport:()=>Qa,axGlobals:()=>X,axModelInfoAnthropic:()=>Jn,axModelInfoCohere:()=>Xr,axModelInfoDeepSeek:()=>Zr,axModelInfoGoogleGemini:()=>ro,axModelInfoGrok:()=>yo,axModelInfoGroq:()=>so,axModelInfoHuggingFace:()=>io,axModelInfoMistral:()=>lo,axModelInfoOpenAI:()=>Xt,axModelInfoOpenAIResponses:()=>Hr,axModelInfoReka:()=>ho,axModelInfoTogether:()=>xo,axModelInfoWebLLM:()=>Ao,axProcessContentForProvider:()=>go,axRAG:()=>zc,axScoreProvidersForRequest:()=>Yr,axSelectOptimalProvider:()=>Qr,axSpanAttributes:()=>Q,axSpanEvents:()=>at,axUpdateMetricsConfig:()=>yl,axUpdateOptimizerMetricsConfig:()=>Cc,axValidateChatRequestMessage:()=>Wt,axValidateChatResponseResult:()=>zr,axValidateProviderCapabilities:()=>Us,f:()=>de,flow:()=>as,s:()=>wc});function Ye({model:i,modelInfo:e,models:t}){let n=t?.find(c=>c.key===i),r=n&&"model"in n?n.model:i,o=e.find(c=>c.name===i);if(o)return o;let s=e.find(c=>c.name===r);if(s)return s;let a=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+$/,""),l=e.find(c=>c.name===a);return l||null}var fs=(()=>{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 Ee(){return fs.randomUUID()}async function ou(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await fs.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var hs=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 s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return ou(this.data)}};function Le(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new hs}function Hi(){return fs}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,`
|
|
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
|
`)?`
|
|
@@ -25,10 +25,10 @@ Body:`,JSON.stringify(e,null,2),`
|
|
|
25
25
|
`,`Status: ${g.status} ${g.statusText}
|
|
26
26
|
`,`
|
|
27
27
|
-------------------------------------------
|
|
28
|
-
`),!g.body)throw new At("Response body is null",u.href,e,{metrics:r},s);let h,f=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(y){let b=g.body.getReader(),C=new TextDecoder,P="";async function
|
|
28
|
+
`),!g.body)throw new At("Response body is null",u.href,e,{metrics:r},s);let h,f=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(y){let b=g.body.getReader(),C=new TextDecoder,P="";async function S(){try{for(;;){let{done:v,value:k}=await b.read();if(v){T=!0,y.close();break}P+=C.decode(k,{stream:!0});let F=P.split(`
|
|
29
29
|
|
|
30
30
|
`);P=F.pop()||"";for(let R of F){if(!R.trim())continue;let w=R.split(`
|
|
31
|
-
`),I="",_="message";for(let k of w)k.startsWith("data: ")?I=k.slice(6):k.startsWith("event: ")&&(_=k.slice(7));if(I){if(I==="[DONE]"){y.close();return}try{let k=JSON.parse(I);h=k,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),y.enqueue(k),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":_})}catch(k){o&&console.warn("Skipping non-JSON SSE data:",I,k)}}}}}catch(v){let M=v,F={...r,streamDuration:Date.now()-r.startTime};M.name==="AbortError"||M.message?.includes("aborted")?y.error(new Qe(u.href,e,h,{streamMetrics:F},s)):y.error(new Ge(M,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:F},s))}finally{b.releaseLock()}}O()}});let A=new TransformStream({transform(y,b){h=y,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),b.enqueue(y),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),T=!1;return new ReadableStream({start(y){let b=g.body.pipeThrough(new iu).pipeThrough(new Fr).pipeThrough(A).getReader();async function C(){try{for(;;){let{done:P,value:O}=await b.read();if(P){T||(T=!0,y.close());break}if(T)break;y.enqueue(O)}}catch(P){let O=P,v={...r,streamDuration:Date.now()-r.startTime};throw O.name==="AbortError"||O.message?.includes("aborted")?y.error(new Qe(u.href,e,h,{streamMetrics:v},s)):O instanceof TypeError&&O.message.includes("cancelled")?y.error(new Qe(u.href,e,h,{streamMetrics:v,cancelReason:"Stream cancelled by client"},s)):y.error(new Ge(O,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:v},s)),O}finally{a&&clearTimeout(a),b.releaseLock()}}C()},cancel(){T=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw i.abortSignal?.aborted?new qt(u.href,i.abortSignal.reason,e,{metrics:r},s):new st(u.href,n||0,e,{metrics:r},s);let h=g;if(!(g instanceof Fe)&&g instanceof Error&&(h=new Ge(g,u.href,e,void 0,{metrics:r},s)),i.span?.isRecording()&&(i.span.recordException(h),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),h instanceof Ge&&Wi(h,void 0,d,t)){let f=Ki(d,t);d++,Vi(r),i.span?.addEvent("retry",{attempt:d,delay:f,error:h.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(x=>setTimeout(x,f));continue}throw h instanceof Fe&&(h.context.metrics=r),h}finally{a!==void 0&&clearTimeout(a)}}};var Ji=typeof globalThis=="object"?globalThis:global;var bt="1.9.0";var Yi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function cu(i){var e=new Set([i]),t=new Set,n=i.match(Yi);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===i};function o(a){return t.add(a),!1}function s(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(Yi);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?s(l):o(l):r.minor<=u.minor?s(l):o(l)}}var Qi=cu(bt);var uu=bt.split(".")[0],Bn=Symbol.for("opentelemetry.js.api."+uu),jn=Ji;function zt(i,e,t,n){var r;n===void 0&&(n=!1);var o=jn[Bn]=(r=jn[Bn])!==null&&r!==void 0?r:{version:bt};if(!n&&o[i]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+i);return t.error(s.stack||s.message),!1}if(o.version!==bt){var s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+i+" does not match previously registered API v"+bt);return t.error(s.stack||s.message),!1}return o[i]=e,t.debug("@opentelemetry/api: Registered a global for "+i+" v"+bt+"."),!0}function It(i){var e,t,n=(e=jn[Bn])===null||e===void 0?void 0:e.version;if(!(!n||!Qi(n)))return(t=jn[Bn])===null||t===void 0?void 0:t[i]}function Ht(i,e){e.debug("@opentelemetry/api: Unregistering a global for "+i+" v"+bt+".");var t=jn[Bn];t&&delete t[i]}var pu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},du=function(i,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 i.concat(o||Array.prototype.slice.call(e))},Xi=function(){function i(e){this._namespace=e.namespace||"DiagComponentLogger"}return i.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("debug",this._namespace,e)},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("error",this._namespace,e)},i.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("info",this._namespace,e)},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("warn",this._namespace,e)},i.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("verbose",this._namespace,e)},i}();function qn(i,e,t){var n=It("diag");if(n)return t.unshift(e),n[i].apply(n,du([],pu(t),!1))}var Ue;(function(i){i[i.NONE=0]="NONE",i[i.ERROR=30]="ERROR",i[i.WARN=50]="WARN",i[i.INFO=60]="INFO",i[i.DEBUG=70]="DEBUG",i[i.VERBOSE=80]="VERBOSE",i[i.ALL=9999]="ALL"})(Ue||(Ue={}));function Zi(i,e){i<Ue.NONE?i=Ue.NONE:i>Ue.ALL&&(i=Ue.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&i>=r?o.bind(e):function(){}}return{error:t("error",Ue.ERROR),warn:t("warn",Ue.WARN),info:t("info",Ue.INFO),debug:t("debug",Ue.DEBUG),verbose:t("verbose",Ue.VERBOSE)}}var mu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},gu=function(i,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 i.concat(o||Array.prototype.slice.call(e))},hu="diag",Kt=function(){function i(){function e(r){return function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=It("diag");if(a)return a[r].apply(a,gu([],mu(o),!1))}}var t=this,n=function(r,o){var s,a,l;if(o===void 0&&(o={logLevel:Ue.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((s=c.stack)!==null&&s!==void 0?s:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=It("diag"),p=Zi((a=o.logLevel)!==null&&a!==void 0?a:Ue.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 zt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){Ht(hu,t)},t.createComponentLogger=function(r){return new Xi(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return i.instance=function(){return this._instance||(this._instance=new i),this._instance},i}();function ea(i){return Symbol.for(i)}var fu=function(){function i(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 i(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new i(t._currentContext);return r._currentContext.delete(n),r}}return i}(),ta=new fu;var xu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},Au=function(i,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 i.concat(o||Array.prototype.slice.call(e))},na=function(){function i(){}return i.prototype.active=function(){return ta},i.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,Au([n],xu(r),!1))},i.prototype.bind=function(e,t){return t},i.prototype.enable=function(){return this},i.prototype.disable=function(){return this},i}();var yu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},bu=function(i,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 i.concat(o||Array.prototype.slice.call(e))},ys="context",Iu=new na,Vt=function(){function i(){}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalContextManager=function(e){return zt(ys,e,Kt.instance())},i.prototype.active=function(){return this._getContextManager().active()},i.prototype.with=function(e,t,n){for(var r,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return(r=this._getContextManager()).with.apply(r,bu([e,t,n],yu(o),!1))},i.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},i.prototype._getContextManager=function(){return It(ys)||Iu},i.prototype.disable=function(){this._getContextManager().disable(),Ht(ys,Kt.instance())},i}();var $r;(function(i){i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED"})($r||($r={}));var bs="0000000000000000",Is="00000000000000000000000000000000",ra={traceId:Is,spanId:bs,traceFlags:$r.NONE};var vt=function(){function i(e){e===void 0&&(e=ra),this._spanContext=e}return i.prototype.spanContext=function(){return this._spanContext},i.prototype.setAttribute=function(e,t){return this},i.prototype.setAttributes=function(e){return this},i.prototype.addEvent=function(e,t){return this},i.prototype.addLink=function(e){return this},i.prototype.addLinks=function(e){return this},i.prototype.setStatus=function(e){return this},i.prototype.updateName=function(e){return this},i.prototype.end=function(e){},i.prototype.isRecording=function(){return!1},i.prototype.recordException=function(e,t){},i}();var Ts=ea("OpenTelemetry Context Key SPAN");function Nr(i){return i.getValue(Ts)||void 0}function oa(){return Nr(Vt.getInstance().active())}function zn(i,e){return i.setValue(Ts,e)}function sa(i){return i.deleteValue(Ts)}function ia(i,e){return zn(i,new vt(e))}function Dr(i){var e;return(e=Nr(i))===null||e===void 0?void 0:e.spanContext()}var Tu=/^([0-9a-f]{32})$/i,Cu=/^[0-9a-f]{16}$/i;function Ru(i){return Tu.test(i)&&i!==Is}function wu(i){return Cu.test(i)&&i!==bs}function Lr(i){return Ru(i.traceId)&&wu(i.spanId)}function aa(i){return new vt(i)}var Cs=Vt.getInstance(),Gr=function(){function i(){}return i.prototype.startSpan=function(e,t,n){n===void 0&&(n=Cs.active());var r=!!t?.root;if(r)return new vt;var o=n&&Dr(n);return vu(o)&&Lr(o)?new vt(o):new vt},i.prototype.startActiveSpan=function(e,t,n,r){var o,s,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,s=n,a=r);var l=s??Cs.active(),c=this.startSpan(e,o,l),u=zn(l,c);return Cs.with(u,a,void 0,c)}},i}();function vu(i){return typeof i=="object"&&typeof i.spanId=="string"&&typeof i.traceId=="string"&&typeof i.traceFlags=="number"}var Su=new Gr,la=function(){function i(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return i.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},i.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},i.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):Su},i}();var ca=function(){function i(){}return i.prototype.getTracer=function(e,t,n){return new Gr},i}();var Ou=new ca,Rs=function(){function i(){}return i.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new la(this,e,t,n)},i.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Ou},i.prototype.setDelegate=function(e){this._delegate=e},i.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},i}();var je;(function(i){i[i.INTERNAL=0]="INTERNAL",i[i.SERVER=1]="SERVER",i[i.CLIENT=2]="CLIENT",i[i.PRODUCER=3]="PRODUCER",i[i.CONSUMER=4]="CONSUMER"})(je||(je={}));var St=Vt.getInstance();var ws="trace",ua=function(){function i(){this._proxyTracerProvider=new Rs,this.wrapSpanContext=aa,this.isSpanContextValid=Lr,this.deleteSpan=sa,this.getSpan=Nr,this.getActiveSpan=oa,this.getSpanContext=Dr,this.setSpan=zn,this.setSpanContext=ia}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalTracerProvider=function(e){var t=zt(ws,this._proxyTracerProvider,Kt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},i.prototype.getTracerProvider=function(){return It(ws)||this._proxyTracerProvider},i.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},i.prototype.disable=function(){Ht(ws,Kt.instance()),this._proxyTracerProvider=new Rs},i}();var Hn=ua.getInstance();var X={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var Be=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 Om=new Be,pa=i=>{console.log(i)},da=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
31
|
+
`),I="",_="message";for(let M of w)M.startsWith("data: ")?I=M.slice(6):M.startsWith("event: ")&&(_=M.slice(7));if(I){if(I==="[DONE]"){y.close();return}try{let M=JSON.parse(I);h=M,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),y.enqueue(M),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":_})}catch(M){o&&console.warn("Skipping non-JSON SSE data:",I,M)}}}}}catch(v){let k=v,F={...r,streamDuration:Date.now()-r.startTime};k.name==="AbortError"||k.message?.includes("aborted")?y.error(new Qe(u.href,e,h,{streamMetrics:F},s)):y.error(new Ge(k,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:F},s))}finally{b.releaseLock()}}S()}});let A=new TransformStream({transform(y,b){h=y,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),b.enqueue(y),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),T=!1;return new ReadableStream({start(y){let b=g.body.pipeThrough(new iu).pipeThrough(new Fr).pipeThrough(A).getReader();async function C(){try{for(;;){let{done:P,value:S}=await b.read();if(P){T||(T=!0,y.close());break}if(T)break;y.enqueue(S)}}catch(P){let S=P,v={...r,streamDuration:Date.now()-r.startTime};throw S.name==="AbortError"||S.message?.includes("aborted")?y.error(new Qe(u.href,e,h,{streamMetrics:v},s)):S instanceof TypeError&&S.message.includes("cancelled")?y.error(new Qe(u.href,e,h,{streamMetrics:v,cancelReason:"Stream cancelled by client"},s)):y.error(new Ge(S,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:v},s)),S}finally{a&&clearTimeout(a),b.releaseLock()}}C()},cancel(){T=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw i.abortSignal?.aborted?new qt(u.href,i.abortSignal.reason,e,{metrics:r},s):new st(u.href,n||0,e,{metrics:r},s);let h=g;if(!(g instanceof Fe)&&g instanceof Error&&(h=new Ge(g,u.href,e,void 0,{metrics:r},s)),i.span?.isRecording()&&(i.span.recordException(h),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),h instanceof Ge&&Wi(h,void 0,d,t)){let f=Ki(d,t);d++,Vi(r),i.span?.addEvent("retry",{attempt:d,delay:f,error:h.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(x=>setTimeout(x,f));continue}throw h instanceof Fe&&(h.context.metrics=r),h}finally{a!==void 0&&clearTimeout(a)}}};var Ji=typeof globalThis=="object"?globalThis:global;var bt="1.9.0";var Yi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function cu(i){var e=new Set([i]),t=new Set,n=i.match(Yi);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===i};function o(a){return t.add(a),!1}function s(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(Yi);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?s(l):o(l):r.minor<=u.minor?s(l):o(l)}}var Qi=cu(bt);var uu=bt.split(".")[0],Bn=Symbol.for("opentelemetry.js.api."+uu),jn=Ji;function zt(i,e,t,n){var r;n===void 0&&(n=!1);var o=jn[Bn]=(r=jn[Bn])!==null&&r!==void 0?r:{version:bt};if(!n&&o[i]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+i);return t.error(s.stack||s.message),!1}if(o.version!==bt){var s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+i+" does not match previously registered API v"+bt);return t.error(s.stack||s.message),!1}return o[i]=e,t.debug("@opentelemetry/api: Registered a global for "+i+" v"+bt+"."),!0}function It(i){var e,t,n=(e=jn[Bn])===null||e===void 0?void 0:e.version;if(!(!n||!Qi(n)))return(t=jn[Bn])===null||t===void 0?void 0:t[i]}function Ht(i,e){e.debug("@opentelemetry/api: Unregistering a global for "+i+" v"+bt+".");var t=jn[Bn];t&&delete t[i]}var pu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},du=function(i,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 i.concat(o||Array.prototype.slice.call(e))},Xi=function(){function i(e){this._namespace=e.namespace||"DiagComponentLogger"}return i.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("debug",this._namespace,e)},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("error",this._namespace,e)},i.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("info",this._namespace,e)},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("warn",this._namespace,e)},i.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return qn("verbose",this._namespace,e)},i}();function qn(i,e,t){var n=It("diag");if(n)return t.unshift(e),n[i].apply(n,du([],pu(t),!1))}var Ue;(function(i){i[i.NONE=0]="NONE",i[i.ERROR=30]="ERROR",i[i.WARN=50]="WARN",i[i.INFO=60]="INFO",i[i.DEBUG=70]="DEBUG",i[i.VERBOSE=80]="VERBOSE",i[i.ALL=9999]="ALL"})(Ue||(Ue={}));function Zi(i,e){i<Ue.NONE?i=Ue.NONE:i>Ue.ALL&&(i=Ue.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&i>=r?o.bind(e):function(){}}return{error:t("error",Ue.ERROR),warn:t("warn",Ue.WARN),info:t("info",Ue.INFO),debug:t("debug",Ue.DEBUG),verbose:t("verbose",Ue.VERBOSE)}}var mu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},gu=function(i,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 i.concat(o||Array.prototype.slice.call(e))},hu="diag",Kt=function(){function i(){function e(r){return function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=It("diag");if(a)return a[r].apply(a,gu([],mu(o),!1))}}var t=this,n=function(r,o){var s,a,l;if(o===void 0&&(o={logLevel:Ue.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((s=c.stack)!==null&&s!==void 0?s:c.message),!1}typeof o=="number"&&(o={logLevel:o});var u=It("diag"),p=Zi((a=o.logLevel)!==null&&a!==void 0?a:Ue.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 zt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){Ht(hu,t)},t.createComponentLogger=function(r){return new Xi(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return i.instance=function(){return this._instance||(this._instance=new i),this._instance},i}();function ea(i){return Symbol.for(i)}var fu=function(){function i(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 i(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new i(t._currentContext);return r._currentContext.delete(n),r}}return i}(),ta=new fu;var xu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},Au=function(i,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 i.concat(o||Array.prototype.slice.call(e))},na=function(){function i(){}return i.prototype.active=function(){return ta},i.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,Au([n],xu(r),!1))},i.prototype.bind=function(e,t){return t},i.prototype.enable=function(){return this},i.prototype.disable=function(){return this},i}();var yu=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},bu=function(i,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 i.concat(o||Array.prototype.slice.call(e))},ys="context",Iu=new na,Vt=function(){function i(){}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalContextManager=function(e){return zt(ys,e,Kt.instance())},i.prototype.active=function(){return this._getContextManager().active()},i.prototype.with=function(e,t,n){for(var r,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return(r=this._getContextManager()).with.apply(r,bu([e,t,n],yu(o),!1))},i.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},i.prototype._getContextManager=function(){return It(ys)||Iu},i.prototype.disable=function(){this._getContextManager().disable(),Ht(ys,Kt.instance())},i}();var $r;(function(i){i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED"})($r||($r={}));var bs="0000000000000000",Is="00000000000000000000000000000000",ra={traceId:Is,spanId:bs,traceFlags:$r.NONE};var vt=function(){function i(e){e===void 0&&(e=ra),this._spanContext=e}return i.prototype.spanContext=function(){return this._spanContext},i.prototype.setAttribute=function(e,t){return this},i.prototype.setAttributes=function(e){return this},i.prototype.addEvent=function(e,t){return this},i.prototype.addLink=function(e){return this},i.prototype.addLinks=function(e){return this},i.prototype.setStatus=function(e){return this},i.prototype.updateName=function(e){return this},i.prototype.end=function(e){},i.prototype.isRecording=function(){return!1},i.prototype.recordException=function(e,t){},i}();var Ts=ea("OpenTelemetry Context Key SPAN");function Nr(i){return i.getValue(Ts)||void 0}function oa(){return Nr(Vt.getInstance().active())}function zn(i,e){return i.setValue(Ts,e)}function sa(i){return i.deleteValue(Ts)}function ia(i,e){return zn(i,new vt(e))}function Dr(i){var e;return(e=Nr(i))===null||e===void 0?void 0:e.spanContext()}var Tu=/^([0-9a-f]{32})$/i,Cu=/^[0-9a-f]{16}$/i;function Ru(i){return Tu.test(i)&&i!==Is}function wu(i){return Cu.test(i)&&i!==bs}function Lr(i){return Ru(i.traceId)&&wu(i.spanId)}function aa(i){return new vt(i)}var Cs=Vt.getInstance(),Gr=function(){function i(){}return i.prototype.startSpan=function(e,t,n){n===void 0&&(n=Cs.active());var r=!!t?.root;if(r)return new vt;var o=n&&Dr(n);return vu(o)&&Lr(o)?new vt(o):new vt},i.prototype.startActiveSpan=function(e,t,n,r){var o,s,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,s=n,a=r);var l=s??Cs.active(),c=this.startSpan(e,o,l),u=zn(l,c);return Cs.with(u,a,void 0,c)}},i}();function vu(i){return typeof i=="object"&&typeof i.spanId=="string"&&typeof i.traceId=="string"&&typeof i.traceFlags=="number"}var Su=new Gr,la=function(){function i(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return i.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},i.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},i.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):Su},i}();var ca=function(){function i(){}return i.prototype.getTracer=function(e,t,n){return new Gr},i}();var Ou=new ca,Rs=function(){function i(){}return i.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new la(this,e,t,n)},i.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Ou},i.prototype.setDelegate=function(e){this._delegate=e},i.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},i}();var je;(function(i){i[i.INTERNAL=0]="INTERNAL",i[i.SERVER=1]="SERVER",i[i.CLIENT=2]="CLIENT",i[i.PRODUCER=3]="PRODUCER",i[i.CONSUMER=4]="CONSUMER"})(je||(je={}));var St=Vt.getInstance();var ws="trace",ua=function(){function i(){this._proxyTracerProvider=new Rs,this.wrapSpanContext=aa,this.isSpanContextValid=Lr,this.deleteSpan=sa,this.getSpan=Nr,this.getActiveSpan=oa,this.getSpanContext=Dr,this.setSpan=zn,this.setSpanContext=ia}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalTracerProvider=function(e){var t=zt(ws,this._proxyTracerProvider,Kt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},i.prototype.getTracerProvider=function(){return It(ws)||this._proxyTracerProvider},i.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},i.prototype.disable=function(){Ht(ws,Kt.instance()),this._proxyTracerProvider=new Rs},i}();var Hn=ua.getInstance();var X={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var Be=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 Om=new Be,pa=i=>{console.log(i)},da=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
32
32
|
${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
|
|
33
33
|
${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
|
|
34
34
|
`;if(typeof i.content=="string")return r+n(i.content,"green");let o=i.content.map(s=>{if(s.type==="text")return n(s.text,"green");if(s.type==="image"){let a=e?"[Image]":`[Image: ${s.image}]`;return n(a,"green")}if(s.type==="audio"){let a=e?"[Audio]":`[Audio: ${s.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
|
|
@@ -165,8 +165,8 @@ ${e}
|
|
|
165
165
|
`,o.description&&(r+=` ${o.description}
|
|
166
166
|
`)}),r+=`${e}
|
|
167
167
|
`;break}default:r=JSON.stringify(n,null,2)}i(r)}};var Q={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"},at={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"},Ss=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Ss||{}),Os=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(Os||{});var ks=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()}},Ur=class extends TransformStream{constructor(e,t){super(new ks(e,t))}};function Br(i,e){for(let t of e){let n=i.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)):i.push(t)}}var ha=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var fa=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function xa(i,e){let t=new Map;for(let n of i)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?Br(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 Aa=(i,e)=>{e({name:"FunctionResults",value:i})},Ms=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},ya=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},ba=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},Ia=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var Ta=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Ca=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},Ra=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var qr=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},_t=(...i)=>{let e={};for(let t of i)t&&Object.assign(e,t);return e},jr,wa=i=>{if(jr)return jr;if(i)return jr=ku(i),jr};var ku=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"}),cacheReadTokensCounter:i.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:i.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),va=(i,e,t,n,r,o)=>{try{if(i.latencyHistogram){let s=qr({operation:e,ai_service:n,...r?{model:r}:{},...o});i.latencyHistogram.record(t,s)}}catch(s){console.warn("Failed to record latency metric:",s)}},Sa=(i,e,t,n,r,o,s,a)=>{let l={operation:e,ai_service:o,...s?{model:s}:{},...a};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,l),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,l),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,l)},Oa=(i,e,t,n,r)=>{try{if(i.errorCounter){let o=qr({operation:e,ai_service:t,...n?{model:n}:{},...r});i.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},ka=(i,e,t,n,r,o)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ma=(i,e,t,n,r)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Kn=(i,e,t,n,r,o)=>{try{let s=qr({ai_service:n,...r?{model:r}:{},...o});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...s}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,s),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,s)}catch(s){console.warn("Failed to record token metric:",s)}},Pa=(i,e,t,n,r,o)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ea=(i,e,t,n,r,o)=>{let s={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...o};i.functionCallsCounter&&i.functionCallsCounter.add(1,s),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,s)},Ps=(i,e,t,n,r,o)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Es=(i,e,t,n,r,o)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Fa=(i,e,t,n,r,o)=>{let s={...n?{ai_service:n}:{},...r?{model:r}:{},...o};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,s),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,s)},Fs=(i,e,t,n,r,o)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},_a=(i,e,t,n,r)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},$a=(i,e,t,n,r)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Na=(i,e,t,n,r)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Da=(i,e,t,n,r)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},La=(i,e,t,n,r)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},Ga=(i,e,t,n,r,o)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...o})},_s=(i,e,t,n,r,o)=>{try{if(t<=0)return;let s=qr({ai_service:n,...r?{model:r}:{},...o});e==="read"&&i.cacheReadTokensCounter&&i.cacheReadTokensCounter.add(t,s),e==="write"&&i.cacheWriteTokensCounter&&i.cacheWriteTokensCounter.add(t,s)}catch(s){console.warn("Failed to record cache token metric:",s)}};function Ua(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function lt(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Ua(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Ua(e.item)}`),new Error(t.join(`
|
|
168
|
-
`))}function Wt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.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 i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.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 i=="object"&&i!==null&&"content"in i?i.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 s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){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(s)}`)}}}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 i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,s=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!s&&!a&&!l&<("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:i}),n!==void 0&&typeof n!="string"&<("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&<("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&<("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&<("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&<("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)lt("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&<("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&<("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&<("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.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)}`);i.isError!==void 0&&typeof i.isError!="boolean"&<("Function message isError must be a boolean when provided",{fieldPath:"isError",value:i.isError,item:i});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function zr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];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.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,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.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let s=r.thoughtBlocks[o];if(typeof s!="object"||s===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(s)}`);if(typeof s.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(s.data)}`);if(typeof s.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(s.encrypted)}`);if(s.signature!==void 0&&typeof s.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(s.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 s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.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 s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.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 $s=new Map;function Mu(i){return`${i.providerName}:${i.contentHash}`}function Pu(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Eu(i){let e=Le("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)Pu(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var ie=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),we=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,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??X.tracer,this.meter=a.meter??X.meter,this.modelInfo=o,this.models=c,this.id=Ee();let u=this.getModel(s.model)??s.model,p=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:p},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&Fu(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=X.logger??ma;corsProxy;retry;customLabels;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 wa(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??X.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??X.tracer,this.meter=e.meter??X.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??X.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,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,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return _t(X.customLabels,this.customLabels,e)}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,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((s,a)=>s+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);va(o,e,t,this.name,s,a),Sa(o,e,r.mean,r.p95,r.p99,this.name,s,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Ma(o,e,this.name,s,a),t&&Oa(o,e,this.name,s,a),ka(o,e,r.rate,this.name,s,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:o,totalTokens:s,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:c}=e.tokens,u=this.getMergedCustomLabels(t);r&&Kn(n,"input",r,this.name,e.model,u),o&&Kn(n,"output",o,this.name,e.model,u),s&&Kn(n,"total",s,this.name,e.model,u),a&&Kn(n,"thoughts",a,this.name,e.model,u),l&&_s(n,"read",l,this.name,e.model,u),c&&_s(n,"write",c,this.name,e.model,u)}}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,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/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,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Ea(r,o.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Na(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Da(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=s?.stream??!1;Pa(r,"chat",l,this.name,o,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);Ga(r,c,u,this.name,o,a);let p=this.calculatePromptLength(e);_a(r,p,this.name,o,a),Fa(r,s?.temperature,s?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&La(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(Ps(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(Es(r,"chat",g,this.name,o,a),m.results)for(let x of m.results)x.functionCalls&&this.recordFunctionCallMetrics(x.functionCalls,this.lastUsedChatModel,a);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);h>0&&$a(r,h,this.name,o,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&Fs(r,"chat",f,this.name,o,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedEmbedModel,s=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);Ps(r,"embed",a,this.name,o,s);let l=this.calculateResponseSize(t);Es(r,"embed",l,this.name,o,s);let c=this.estimateCostByName(o,t.modelUsage);c>0&&Fs(r,"embed",c,this.name,o,s)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.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",l?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),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)Wt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.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:je.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"chat",[Q.LLM_REQUEST_MODEL]:n,[Q.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[Q.LLM_REQUEST_TEMPERATURE]:o.temperature,[Q.LLM_REQUEST_TOP_P]:o.topP??"Not set",[Q.LLM_REQUEST_TOP_K]:o.topK??"Not set",[Q.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[Q.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[Q.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[Q.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??St.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 s=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(T=>this.cleanupFunctionSchema(T)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&ha(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(T=>{if(T.role==="assistant"){let{content:y,name:b,cache:C}=T;return{role:"assistant",content:y,name:b,cache:C}}return T.role==="function"?{role:"user",content:T.result}:T}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,o),h=async()=>{if(g?.preparedRequest){let{apiConfig:C,request:P}=g.preparedRequest;return o?.isRecording()&&Ba(n,o,this.excludeContentFromTrace),await _e({name:C.name,url:this.apiURL,localCall:C.localCall,headers:await this.buildHeaders(C.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},P)}let[T,y]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Ba(n,o,this.excludeContentFromTrace),await _e({name:T.name,url:this.apiURL,localCall:T.localCall,headers:await this.buildHeaders(T.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},y)},f=r?.rateLimiter??this.rt,x=f?await f(h,{modelUsage:this.modelUsage}):await h();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let T=this.aiImpl.createChatStreamResp.bind(this),y=O=>v=>{let M=T(v,O);if(M.sessionId=r?.sessionId,!M.modelUsage){let F=this.aiImpl.getTokenUsage();F&&(M.modelUsage={ai:this.name,model:e,tokens:F})}return this.modelUsage=M.modelUsage,this.recordTokenUsage(M.modelUsage,r?.customLabels),o?.isRecording()&&ja(M,o,this.excludeContentFromTrace),M},b=async O=>{o?.isRecording()&&o.end(),s&&xa(O,r?.logger??this.logger)};if(typeof window<"u"){let O=x,v={},M=[],F=r?.abortSignal??this.abortSignal;return new ReadableStream({start:R=>{let w=O.getReader(),I=()=>{try{w.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{o?.isRecording()&&o.end()}catch{}try{R.error(new DOMException("Aborted","AbortError"))}catch{R.error(new Error("Aborted"))}};if(F){if(F.aborted){I();return}F.addEventListener("abort",I,{once:!0})}async function _(){try{for(;;){let{done:k,value:S}=await w.read();if(k){b&&await b(M),R.close();break}let E=y(v)(S);E&&(M.push(E),R.enqueue(E))}}catch(k){if(R.error(k),o?.isRecording())try{o.end()}catch{}}finally{if(w.releaseLock(),F)try{F.removeEventListener("abort",I)}catch{}}}_()}})}return x.pipeThrough(new Ur(y({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let A=this.aiImpl.createChatResp(x);if(A.sessionId=r?.sessionId,!A.modelUsage){let T=this.aiImpl.getTokenUsage();T&&(A.modelUsage={ai:this.name,model:e,tokens:T})}return A.modelUsage&&(this.modelUsage=A.modelUsage,this.recordTokenUsage(A.modelUsage,r?.customLabels)),o?.isRecording()&&(ja(A,o,this.excludeContentFromTrace),o.end()),s&&fa(A,r?.logger??this.logger),A}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.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",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&o&&this.recordEmbedMetrics(e,o,a)}}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:je.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"embeddings",[Q.LLM_REQUEST_MODEL]:n}},t?.traceContext??St.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),s=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&Ta(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await o(l);return await _e({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(at.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Ca(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}async handleContextCaching(e,t,n,r){let o=n?.contextCache;if(!o)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let l=o.ttlSeconds??3600,c=o.refreshWindowSeconds??300,u=o.minTokens??2048;if(o.name)return this.useCacheByName(e,t,o.name,n,r);let p=Eu(t.chatPrompt);if(!p||p===Le("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=Mu(d),g=Date.now(),h=o.registry,f=h?await h.get(m):$s.get(m);if(f&&f.expiresAt>g){if(f.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let y={cacheName:f.cacheName,expiresAt:g+l*1e3,tokenCount:f.tokenCount};h?await h.set(m,y):$s.set(m,{...y,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let A=this.aiImpl.buildCacheCreateOp?.(t,n);if(A){let T=await this.executeCacheOperation(A,n,r);if(T){let y={cacheName:T.name,expiresAt:new Date(T.expiresAt).getTime(),tokenCount:T.tokenCount};return h?await h.set(m,y):$s.set(m,{...y,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,T.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let s=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:s.apiConfig,request:s.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let o=await _e({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(o)}catch(o){n?.addEvent("context_cache.error",{type:e.type,error:o instanceof Error?o.message:String(o)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)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)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Ba(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(at.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(at.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(at.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(at.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
|
|
169
|
-
`)),e.addEvent(at.GEN_AI_USER_MESSAGE,r)}function ja(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[Q.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(at.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.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})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(at.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function qa(i){let e=0;for(let t of i){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 Fu(i){let e=new Set;for(let t of i){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 Vn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(Vn||{}),Wn=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))(Wn||{});var Jn=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",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,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,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 Ot=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Ot(r)]))),e.items&&(e.items=Ot(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Ot(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Ot(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Ot(n))),e},Ds=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),Ha=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),Ns=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={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.some(M=>"cache"in M&&M.cache)||e.functions?.some(M=>M.cache),l=e.chatPrompt.filter(M=>M.role==="system"),c=l.map((M,F)=>({type:"text",text:M.content,...M.cache||a&&F===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(M=>M.role!=="system"),p=e.functions?.map((M,F,R)=>{let w={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},I=M.parameters?Ot(M.parameters):void 0;return I===void 0||I&&typeof I=="object"&&Object.keys(I).length===0?I={...w}:I&&typeof I=="object"&&I.type==="object"&&(!("properties"in I)||!I.properties||Object.keys(I.properties).length===0)&&(I={...I,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:M.name,description:M.description,input_schema:I,...M.cache||a&&F===R.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(M=>M&&typeof M=="object"&&"type"in M?M:{name:M.name,description:M.description,input_schema:M.input_schema?Ot(M.input_schema):void 0,...M.cache_control?{cache_control:M.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let h=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,x=e.modelConfig?.temperature,A=e.modelConfig?.topP,T=e.modelConfig?.topK??this.config.topK,y=e.modelConfig?.n??this.config.n;if(y&&y>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 M=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:M?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:M?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:M?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:M?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:M?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let M=this.config.thinkingTokenBudgetLevels}let C=_u(u,!!b);C.some(M=>M.role==="assistant"&&Array.isArray(M.content)&&M.content.length>0&&M.content[0]?.type==="tool_use")&&(b=void 0);let O;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let M=e.responseFormat.schema.schema||e.responseFormat.schema;O={type:"json_schema",schema:Ot(M)},this.usedStructuredOutput=!0}let v={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...h?{max_tokens:h}:{},...f&&f.length>0?{stop_sequences:f}:{},...x!==void 0&&!b?{temperature:x}:{},...A!==void 0&&(!b||A>=.95)?{top_p:A}:{},...T&&!b?{top_k:T}:{},...s,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...b?{thinking:b}:{},...O?{output_format:O}:{},messages:C};return[o,v]};createChatResp=e=>{if(e.type==="error")throw new Ae(e.error.message,void 0,void 0);let t=za(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;s.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;s.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),s.length>0&&(l.thoughtBlocks=s,l.thought=s.map(u=>u.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let c=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:c,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 Ae(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.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,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{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 s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}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 s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.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,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:za(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},Jt=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){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==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={...Ds(),...r},p=new Ns(u,a),d=g=>{let h=Ye({model:g,modelInfo:Jn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!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"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,f=h?.config;if(!f)return g;let x={};f.maxTokens!==void 0&&(x.maxTokens=f.maxTokens),f.temperature!==void 0&&(x.temperature=f.temperature),f.topP!==void 0&&(x.topP=f.topP),f.topK!==void 0&&(x.topK=f.topK),f.presencePenalty!==void 0&&(x.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(x.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(x.stopSequences=f.stopSequences),f.endSequences!==void 0&&(x.endSequences=f.endSequences),f.stream!==void 0&&(x.stream=f.stream),f.n!==void 0&&(x.n=f.n);let A={...h};Object.keys(x).length>0&&(A.modelConfig={...h.modelConfig??{},...x});let T=f.thinking?.thinkingTokenBudget;if(typeof T=="number"){let y=u.thinkingTokenBudgetLevels,b=[["minimal",y?.minimal??200],["low",y?.low??800],["medium",y?.medium??5e3],["high",y?.high??1e4],["highest",y?.highest??24500]],C="minimal",P=Number.POSITIVE_INFINITY;for(let[O,v]of b){let M=Math.abs(T-v);M<P&&(P=M,C=O)}A.thinkingTokenBudget=C}return f.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!f.thinking.includeThoughts),A});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Jn,defaults:{model:u.model},options:o,supportFor:d,models:m??s})}};function _u(i,e){let t=i.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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?s.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):s.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,c=o[l];c&&c.type==="text"&&(o[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=$u(t);return Nu(n)}function $u(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function Nu(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function za(i){if(i)switch(i){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 Yn=(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.GPT5Pro="gpt-5-pro",R.GPT51="gpt-5.1",R.GPT51ChatLatest="gpt-5.1-chat-latest",R.GPT52="gpt-5.2",R.GPT52ChatLatest="gpt-5.2-chat-latest",R.GPT52Pro="gpt-5.2-pro",R.O1="o1",R.O1Mini="o1-mini",R.O3="o3",R.O3Mini="o3-mini",R.O4Mini="o4-mini",R))(Yn||{}),Yt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Yt||{});var Qt=(I=>(I.GPT4="gpt-4",I.GPT41="gpt-4.1",I.GPT41Mini="gpt-4.1-mini",I.GPT41Nano="gpt-4.1-nano",I.GPT4O="gpt-4o",I.GPT4OMini="gpt-4o-mini",I.GPT4ChatGPT4O="chatgpt-4o-latest",I.GPT4Turbo="gpt-4-turbo",I.GPT35Turbo="gpt-3.5-turbo",I.GPT35TurboInstruct="gpt-3.5-turbo-instruct",I.GPT35TextDavinci002="text-davinci-002",I.GPT3TextBabbage002="text-babbage-002",I.GPT3TextAda001="text-ada-001",I.GPT5="gpt-5",I.GPT5Nano="gpt-5-nano",I.GPT5Mini="gpt-5-mini",I.GPT5Chat="gpt-5-chat",I.GPT5Pro="gpt-5-pro",I.GPT51="gpt-5.1",I.GPT51ChatLatest="gpt-5.1-chat-latest",I.GPT52="gpt-5.2",I.GPT52ChatLatest="gpt-5.2-chat-latest",I.GPT52Pro="gpt-5.2-pro",I.O1Pro="o1-pro",I.O1="o1",I.O1Mini="o1-mini",I.O3Pro="o3-pro",I.O3="o3",I.O3Mini="o3-mini",I.O4Mini="o4-mini",I))(Qt||{});var Xt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{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}],Hr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Du=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},$t=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ie()}),Kr=()=>structuredClone({...$t(),model:"gpt-5"}),Vr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),Wr=()=>({...$t(),model:"gpt-5-nano"}),Ls=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}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Lu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=Du(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...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 Ae(a.message.refusal,e.model,e.id);let l=Ka(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 s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(p)throw new Ae(p,void 0,n);let f=Ka(h),x=d?.map(({id:A,index:T,function:{name:y,arguments:b}})=>{typeof A=="string"&&typeof T=="number"&&!s.indexIdMap[T]&&(s.indexIdMap[T]=A);let C=s.indexIdMap[T];return C?{id:C,type:"function",function:{name:y,params:b}}:null}).filter(A=>A!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,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)}}},Ka=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Lu(i){return i.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 Te=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Ls(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:s})}},Zt=class extends Te{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Xt,...s??[]];let a=c=>{let u=Ye({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!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 h=p?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[T,y]of f){let b=Math.abs(h-y);b<A&&(A=b,x=T)}g.thinkingTokenBudget=x}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...$t(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Gu=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},Uu=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Gs=$t,Va=Vr,Wa=Wr,Ja=Kr,en=class extends Te{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,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={...Gs(),...o},u=Gu(r),p=Uu(u);l=[...Xt,...l??[]];let d=g=>{let h=Ye({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:p&&(h?.supported?.structuredOutputs??!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:h?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Jr=class i{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.");Bu(e),this.services=[...e].sort(t?.comparator??i.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 i(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(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}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){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!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:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={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}}},t=0,n=0,r=0,o=0;for(let s of this.services){let a=s.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,o+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let s of this.services){let a=s.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,s=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=s}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,s=r?.requiresAudio,a=this.services,l=e.model;if((n||o||s)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||s&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),s&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Fe))throw p;switch(p.constructor){case yt:throw p;case We:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Ge:break;case At:break;case Qe:break;case st:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Fe)||r instanceof We&&![408,429,500,502,503,504].includes(r.status)||r instanceof yt)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let s=this.getNextService(this.services,n);if(!s.service)throw r;this.currentService=s.service,n=s.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Bu(i){let e=i.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<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.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 Nt(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.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 i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function Us(i,e){let t=i.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 Yr(i,e){return i.map(t=>{let n=t.getFeatures(),r=Us(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.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,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.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:s}}).sort((t,n)=>n.score-t.score)}function Qr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Nt(i),r=Yr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.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 Ya(i,e){let t=Nt(i),n=Yr(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,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Qa(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Xa(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var Qn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Qn||{}),Xn=(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))(Xn||{});var Xr=[{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 js=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ie()}),el=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),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,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 s=ju(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:s,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}}},tn=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...js(),...t},s=new Bs(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(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Xr,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 ju(i){return i.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=Za(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=Za(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 Za(i){return i?.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 Zn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Zn||{});var Zr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var qs=()=>structuredClone({model:"deepseek-chat",...ie()}),tl=()=>structuredClone({model:"deepseek-coder",...Se()}),nn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...qs(),...t};o=[...Zr,...o??[]],super({apiKey:e,config:s,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 er=(A=>(A.Gemini3Flash="gemini-3-flash-preview",A.Gemini3Pro="gemini-3-pro-preview",A.Gemini3ProImage="gemini-3-pro-image-preview",A.Gemini25Pro="gemini-2.5-pro",A.Gemini25Flash="gemini-2.5-flash",A.Gemini25FlashLite="gemini-2.5-flash-lite",A.Gemini20Flash="gemini-2.0-flash",A.Gemini20FlashLite="gemini-2.0-flash-lite",A.Gemini20ProExp="gemini-2.0-pro-exp-02-05",A.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",A.Gemini1Pro="gemini-1.0-pro",A.Gemini15Flash="gemini-1.5-flash",A.Gemini15Flash002="gemini-1.5-flash-002",A.Gemini15Flash8B="gemini-1.5-flash-8b",A.Gemini15Pro="gemini-1.5-pro",A.GeminiFlashLatest="gemini-flash-latest",A.GeminiFlashLiteLatest="gemini-flash-lite-latest",A.GeminiProLatest="gemini-pro-latest",A))(er||{}),eo=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(eo||{}),to=(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))(to||{}),no=(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))(no||{}),zs=(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))(zs||{}),nl=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var ro=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var oo=i=>{if(!i||typeof i!="object")return i;let e={...i};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,oo(n)]))),e.items&&(e.items=oo(e.items)),e},rl=[{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"}],Ks=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:rl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...ie()}),ol=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:rl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Se()}),Hs=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 x=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${A}`}let s=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<c.length;x++){let A=c[x];switch(A.role){case"user":{let T=Array.isArray(A.content)?A.content.map((y,b)=>{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: ${b})`)}}):[{text:A.content}];l.push({role:"user",parts:T});break}case"assistant":{let T=[],y=A.thoughtBlocks,b=A.functionCalls&&A.functionCalls.length>0,C=y?.[0],P=y?.map(v=>v.data).join("")??"",O=C?.signature;if(P&&T.push({...b?{}:{thought:!0},text:P,...O&&!b?{thought_signature:O}:{}}),A.functionCalls){let v=A.functionCalls.map((M,F)=>{let R;if(typeof M.function.params=="string"){let I=M.function.params;if(I.trim().length===0)R={};else try{R=JSON.parse(I)}catch{throw new Error(`Failed to parse function params JSON: ${I}`)}}else R=M.function.params;let w={functionCall:{name:M.function.name,args:R}};return O&&F===0&&(w.thought_signature=O),w});T.push(...v)}if(A.content&&T.push({text:A.content}),T.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:T});break}case"function":{let T=[],y=A,b=x;for(;;){if(!("functionId"in y))throw new Error(`Chat prompt functionId is empty (index: ${b})`);if(T.push({functionResponse:{name:y.functionId,response:{result:y.result}}}),b+1<c.length&&c[b+1].role==="function")b++,y=c[b];else break}x=b,l.push({role:"user",parts:T});break}default:throw new Error(`Invalid role: ${JSON.stringify(A)} (index: ${x})`)}}let u=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(A=>{let T={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},y=A.parameters?oo(A.parameters):void 0;return y===void 0||y&&typeof y=="object"&&Object.keys(y).length===0?y={...T}: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:[]}),{name:A.name,description:A.description,parameters:y}});u.push({function_declarations:x})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,A=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};u.push({google_maps:A})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.config.thinkingTokenBudgetLevels,A=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=x?.minimal??200,A&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=x?.low??800,A&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=x?.medium??5e3,A&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=x?.high??1e4,A&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=x?.highest??24500,A&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={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(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=oo(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new Ae("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new Ae("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new Ae("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new Ae("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new Ae("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new Ae("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new Ae("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new Ae("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new Ae("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){s.thought=c.text;let u=c.thoughtSignature||c.thought_signature;s.thoughtBlocks||(s.thoughtBlocks=[]),s.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else s.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!s.thoughtBlocks||s.thoughtBlocks.length===0)s.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=s.thoughtBlocks[s.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}s.functionCalls=[...s.functionCalls??[],{id:Ee(),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;s.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&&(s.citations=[...s.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return s});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});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}};supportsContextCache=e=>{let t=e;return nl.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:s}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!s||s.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),s&&s.length>0&&(a.contents=s);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let o=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${o}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:o=>{let s=o;if(s?.name)return{name:s.name,expiresAt:s.expireTime,tokenCount:s.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,o=e.modelConfig?.stream??this.config.stream,{dynamicContents:s,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:o?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=o?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={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"},u=this.config.safetySettings,p={contents:s,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if("cache"in s&&s.cache){r=o;break}}for(let o=0;o<e.length;o++){let s=e[o];if(s.role==="system"){t={role:"user",parts:[{text:s.content}]};continue}if(r>=0&&o<=r)if(s.role==="user"){let a=[];if(typeof s.content=="string")a.push({text:s.content});else if(Array.isArray(s.content))for(let l of s.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else s.role==="assistant"&&s.content&&n.push({role:"model",parts:[{text:s.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if(!("cache"in s&&s.cache))switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else if(r.role==="assistant"){let o=[];if(r.content&&o.push({text:r.content}),r.functionCalls)for(let s of r.functionCalls){let a;if(typeof s.function.params=="string")try{a=JSON.parse(s.function.params)}catch{a={}}else a=s.function.params??{};o.push({functionCall:{name:s.function.name,args:a}})}o.length>0&&n.push({role:"model",parts:o})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},rn=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,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 f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,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={...Ks(),...o},m=new Hs(d,c,r,e,s);l=[...ro,...l??[]];let g=f=>{let x=Ye({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,structuredOutputs:x?.supported?.structuredOutputs??!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:m.supportsContextCache(f),types:["persistent"]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let x=f,A=x?.config;if(!A)return f;let T={};A.maxTokens!==void 0&&(T.maxTokens=A.maxTokens),A.temperature!==void 0&&(T.temperature=A.temperature),A.topP!==void 0&&(T.topP=A.topP),A.topK!==void 0&&(T.topK=A.topK),A.presencePenalty!==void 0&&(T.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(T.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(T.stopSequences=A.stopSequences),A.endSequences!==void 0&&(T.endSequences=A.endSequences),A.stream!==void 0&&(T.stream=A.stream),A.n!==void 0&&(T.n=A.n);let y={...x};Object.keys(T).length>0&&(y.modelConfig={...x.modelConfig??{},...T});let b=A.thinking?.thinkingTokenBudget;if(typeof b=="number"){let C=d.thinkingTokenBudgetLevels,P=[["minimal",C?.minimal??200],["low",C?.low??800],["medium",C?.medium??5e3],["high",C?.high??1e4],["highest",C?.highest??24500]],O="minimal",v=Number.POSITIVE_INFINITY;for(let[M,F]of P){let R=Math.abs(b-F);R<v&&(v=R,O=M)}y.thinkingTokenBudget=O}return A.thinking?.includeThoughts!==void 0&&(y.showThoughts=!!A.thinking.includeThoughts),y});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:h??a})}};var qu=new Be,on=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(qu.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 tr=(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))(tr||{});var so=[{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 zu=()=>structuredClone({model:"llama-3.3-70b-versatile",...ie()}),sn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...zu(),...t},a={...n,streamingUsage:!1};o=[...so,...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:s,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 on(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var io=[];var ao=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(ao||{});var Ws=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ie()}),sl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),Vs=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:
|
|
168
|
+
`))}function Wt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.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 i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.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 i=="object"&&i!==null&&"content"in i?i.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 s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){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(s)}`)}}}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 i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,s=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!s&&!a&&!l&<("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:i}),n!==void 0&&typeof n!="string"&<("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&<("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&<("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&<("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&<("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)lt("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&<("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&<("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&<("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.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)}`);i.isError!==void 0&&typeof i.isError!="boolean"&<("Function message isError must be a boolean when provided",{fieldPath:"isError",value:i.isError,item:i});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function zr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];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.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,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.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let s=r.thoughtBlocks[o];if(typeof s!="object"||s===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(s)}`);if(typeof s.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(s.data)}`);if(typeof s.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(s.encrypted)}`);if(s.signature!==void 0&&typeof s.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(s.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 s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.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 s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.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 $s=new Map;function Mu(i){return`${i.providerName}:${i.contentHash}`}function Pu(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Eu(i){let e=Le("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)Pu(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var ie=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),we=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,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??X.tracer,this.meter=a.meter??X.meter,this.modelInfo=o,this.models=c,this.id=Ee();let u=this.getModel(s.model)??s.model,p=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:p},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&Fu(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=X.logger??ma;corsProxy;retry;customLabels;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 wa(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??X.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??X.tracer,this.meter=e.meter??X.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??X.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,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,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return _t(X.customLabels,this.customLabels,e)}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,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((s,a)=>s+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);va(o,e,t,this.name,s,a),Sa(o,e,r.mean,r.p95,r.p99,this.name,s,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Ma(o,e,this.name,s,a),t&&Oa(o,e,this.name,s,a),ka(o,e,r.rate,this.name,s,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:o,totalTokens:s,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:c}=e.tokens,u=this.getMergedCustomLabels(t);r&&Kn(n,"input",r,this.name,e.model,u),o&&Kn(n,"output",o,this.name,e.model,u),s&&Kn(n,"total",s,this.name,e.model,u),a&&Kn(n,"thoughts",a,this.name,e.model,u),l&&_s(n,"read",l,this.name,e.model,u),c&&_s(n,"write",c,this.name,e.model,u)}}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,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/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,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Ea(r,o.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Na(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Da(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=s?.stream??!1;Pa(r,"chat",l,this.name,o,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);Ga(r,c,u,this.name,o,a);let p=this.calculatePromptLength(e);_a(r,p,this.name,o,a),Fa(r,s?.temperature,s?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&La(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(Ps(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(Es(r,"chat",g,this.name,o,a),m.results)for(let x of m.results)x.functionCalls&&this.recordFunctionCallMetrics(x.functionCalls,this.lastUsedChatModel,a);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);h>0&&$a(r,h,this.name,o,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&Fs(r,"chat",f,this.name,o,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedEmbedModel,s=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);Ps(r,"embed",a,this.name,o,s);let l=this.calculateResponseSize(t);Es(r,"embed",l,this.name,o,s);let c=this.estimateCostByName(o,t.modelUsage);c>0&&Fs(r,"embed",c,this.name,o,s)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.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",l?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),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)Wt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.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:je.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"chat",[Q.LLM_REQUEST_MODEL]:n,[Q.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[Q.LLM_REQUEST_TEMPERATURE]:o.temperature,[Q.LLM_REQUEST_TOP_P]:o.topP??"Not set",[Q.LLM_REQUEST_TOP_K]:o.topK??"Not set",[Q.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[Q.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[Q.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[Q.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??St.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 s=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(T=>this.cleanupFunctionSchema(T)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&ha(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(T=>{if(T.role==="assistant"){let{content:y,name:b,cache:C}=T;return{role:"assistant",content:y,name:b,cache:C}}return T.role==="function"?{role:"user",content:T.result}:T}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,o),h=async()=>{if(g?.preparedRequest){let{apiConfig:C,request:P}=g.preparedRequest;return o?.isRecording()&&Ba(n,o,this.excludeContentFromTrace),await _e({name:C.name,url:this.apiURL,localCall:C.localCall,headers:await this.buildHeaders(C.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},P)}let[T,y]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Ba(n,o,this.excludeContentFromTrace),await _e({name:T.name,url:this.apiURL,localCall:T.localCall,headers:await this.buildHeaders(T.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},y)},f=r?.rateLimiter??this.rt,x=f?await f(h,{modelUsage:this.modelUsage}):await h();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let T=this.aiImpl.createChatStreamResp.bind(this),y=S=>v=>{let k=T(v,S);if(k.sessionId=r?.sessionId,!k.modelUsage){let F=this.aiImpl.getTokenUsage();F&&(k.modelUsage={ai:this.name,model:e,tokens:F})}return this.modelUsage=k.modelUsage,this.recordTokenUsage(k.modelUsage,r?.customLabels),o?.isRecording()&&ja(k,o,this.excludeContentFromTrace),k},b=async S=>{o?.isRecording()&&o.end(),s&&xa(S,r?.logger??this.logger)};if(typeof window<"u"){let S=x,v={},k=[],F=r?.abortSignal??this.abortSignal;return new ReadableStream({start:R=>{let w=S.getReader(),I=()=>{try{w.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{o?.isRecording()&&o.end()}catch{}try{R.error(new DOMException("Aborted","AbortError"))}catch{R.error(new Error("Aborted"))}};if(F){if(F.aborted){I();return}F.addEventListener("abort",I,{once:!0})}async function _(){try{for(;;){let{done:M,value:O}=await w.read();if(M){b&&await b(k),R.close();break}let E=y(v)(O);E&&(k.push(E),R.enqueue(E))}}catch(M){if(R.error(M),o?.isRecording())try{o.end()}catch{}}finally{if(w.releaseLock(),F)try{F.removeEventListener("abort",I)}catch{}}}_()}})}return x.pipeThrough(new Ur(y({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let A=this.aiImpl.createChatResp(x);if(A.sessionId=r?.sessionId,!A.modelUsage){let T=this.aiImpl.getTokenUsage();T&&(A.modelUsage={ai:this.name,model:e,tokens:T})}return A.modelUsage&&(this.modelUsage=A.modelUsage,this.recordTokenUsage(A.modelUsage,r?.customLabels)),o?.isRecording()&&(ja(A,o,this.excludeContentFromTrace),o.end()),s&&fa(A,r?.logger??this.logger),A}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.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",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&o&&this.recordEmbedMetrics(e,o,a)}}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:je.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"embeddings",[Q.LLM_REQUEST_MODEL]:n}},t?.traceContext??St.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),s=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&Ta(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await o(l);return await _e({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(at.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Ca(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}async handleContextCaching(e,t,n,r){let o=n?.contextCache;if(!o)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let l=o.ttlSeconds??3600,c=o.refreshWindowSeconds??300,u=o.minTokens??2048;if(o.name)return this.useCacheByName(e,t,o.name,n,r);let p=Eu(t.chatPrompt);if(!p||p===Le("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=Mu(d),g=Date.now(),h=o.registry,f=h?await h.get(m):$s.get(m);if(f&&f.expiresAt>g){if(f.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let y={cacheName:f.cacheName,expiresAt:g+l*1e3,tokenCount:f.tokenCount};h?await h.set(m,y):$s.set(m,{...y,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let A=this.aiImpl.buildCacheCreateOp?.(t,n);if(A){let T=await this.executeCacheOperation(A,n,r);if(T){let y={cacheName:T.name,expiresAt:new Date(T.expiresAt).getTime(),tokenCount:T.tokenCount};return h?await h.set(m,y):$s.set(m,{...y,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,T.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let s=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:s.apiConfig,request:s.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let o=await _e({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(o)}catch(o){n?.addEvent("context_cache.error",{type:e.type,error:o instanceof Error?o.message:String(o)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)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)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Ba(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(at.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(at.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(at.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(at.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
|
|
169
|
+
`)),e.addEvent(at.GEN_AI_USER_MESSAGE,r)}function ja(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[Q.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(at.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.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})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(at.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function qa(i){let e=0;for(let t of i){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 Fu(i){let e=new Set;for(let t of i){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 Vn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(Vn||{}),Wn=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))(Wn||{});var Jn=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",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,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,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 Ot=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Ot(r)]))),e.items&&(e.items=Ot(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Ot(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Ot(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Ot(n))),e},Ds=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),Ha=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),Ns=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={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.some(k=>"cache"in k&&k.cache)||e.functions?.some(k=>k.cache),l=e.chatPrompt.filter(k=>k.role==="system"),c=l.map((k,F)=>({type:"text",text:k.content,...k.cache||a&&F===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(k=>k.role!=="system"),p=e.functions?.map((k,F,R)=>{let w={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},I=k.parameters?Ot(k.parameters):void 0;return I===void 0||I&&typeof I=="object"&&Object.keys(I).length===0?I={...w}:I&&typeof I=="object"&&I.type==="object"&&(!("properties"in I)||!I.properties||Object.keys(I.properties).length===0)&&(I={...I,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:k.name,description:k.description,input_schema:I,...k.cache||a&&F===R.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(k=>k&&typeof k=="object"&&"type"in k?k:{name:k.name,description:k.description,input_schema:k.input_schema?Ot(k.input_schema):void 0,...k.cache_control?{cache_control:k.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let h=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,x=e.modelConfig?.temperature,A=e.modelConfig?.topP,T=e.modelConfig?.topK??this.config.topK,y=e.modelConfig?.n??this.config.n;if(y&&y>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 k=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:k?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:k?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:k?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:k?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:k?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let k=this.config.thinkingTokenBudgetLevels}let C=_u(u,!!b);C.some(k=>k.role==="assistant"&&Array.isArray(k.content)&&k.content.length>0&&k.content[0]?.type==="tool_use")&&(b=void 0);let S;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let k=e.responseFormat.schema.schema||e.responseFormat.schema;S={type:"json_schema",schema:Ot(k)},this.usedStructuredOutput=!0}let v={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...h?{max_tokens:h}:{},...f&&f.length>0?{stop_sequences:f}:{},...x!==void 0&&!b?{temperature:x}:{},...A!==void 0&&(!b||A>=.95)?{top_p:A}:{},...T&&!b?{top_k:T}:{},...s,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...b?{thinking:b}:{},...S?{output_format:S}:{},messages:C};return[o,v]};createChatResp=e=>{if(e.type==="error")throw new Ae(e.error.message,void 0,void 0);let t=za(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;s.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;s.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),s.length>0&&(l.thoughtBlocks=s,l.thought=s.map(u=>u.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let c=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:c,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 Ae(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.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,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{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 s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}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 s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.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,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:za(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},Jt=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){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==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={...Ds(),...r},p=new Ns(u,a),d=g=>{let h=Ye({model:g,modelInfo:Jn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!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"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,f=h?.config;if(!f)return g;let x={};f.maxTokens!==void 0&&(x.maxTokens=f.maxTokens),f.temperature!==void 0&&(x.temperature=f.temperature),f.topP!==void 0&&(x.topP=f.topP),f.topK!==void 0&&(x.topK=f.topK),f.presencePenalty!==void 0&&(x.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(x.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(x.stopSequences=f.stopSequences),f.endSequences!==void 0&&(x.endSequences=f.endSequences),f.stream!==void 0&&(x.stream=f.stream),f.n!==void 0&&(x.n=f.n);let A={...h};Object.keys(x).length>0&&(A.modelConfig={...h.modelConfig??{},...x});let T=f.thinking?.thinkingTokenBudget;if(typeof T=="number"){let y=u.thinkingTokenBudgetLevels,b=[["minimal",y?.minimal??200],["low",y?.low??800],["medium",y?.medium??5e3],["high",y?.high??1e4],["highest",y?.highest??24500]],C="minimal",P=Number.POSITIVE_INFINITY;for(let[S,v]of b){let k=Math.abs(T-v);k<P&&(P=k,C=S)}A.thinkingTokenBudget=C}return f.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!f.thinking.includeThoughts),A});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Jn,defaults:{model:u.model},options:o,supportFor:d,models:m??s})}};function _u(i,e){let t=i.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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?s.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):s.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,c=o[l];c&&c.type==="text"&&(o[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=$u(t);return Nu(n)}function $u(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function Nu(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function za(i){if(i)switch(i){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 Yn=(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.GPT5Pro="gpt-5-pro",R.GPT51="gpt-5.1",R.GPT51ChatLatest="gpt-5.1-chat-latest",R.GPT52="gpt-5.2",R.GPT52ChatLatest="gpt-5.2-chat-latest",R.GPT52Pro="gpt-5.2-pro",R.O1="o1",R.O1Mini="o1-mini",R.O3="o3",R.O3Mini="o3-mini",R.O4Mini="o4-mini",R))(Yn||{}),Yt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Yt||{});var Qt=(I=>(I.GPT4="gpt-4",I.GPT41="gpt-4.1",I.GPT41Mini="gpt-4.1-mini",I.GPT41Nano="gpt-4.1-nano",I.GPT4O="gpt-4o",I.GPT4OMini="gpt-4o-mini",I.GPT4ChatGPT4O="chatgpt-4o-latest",I.GPT4Turbo="gpt-4-turbo",I.GPT35Turbo="gpt-3.5-turbo",I.GPT35TurboInstruct="gpt-3.5-turbo-instruct",I.GPT35TextDavinci002="text-davinci-002",I.GPT3TextBabbage002="text-babbage-002",I.GPT3TextAda001="text-ada-001",I.GPT5="gpt-5",I.GPT5Nano="gpt-5-nano",I.GPT5Mini="gpt-5-mini",I.GPT5Chat="gpt-5-chat",I.GPT5Pro="gpt-5-pro",I.GPT51="gpt-5.1",I.GPT51ChatLatest="gpt-5.1-chat-latest",I.GPT52="gpt-5.2",I.GPT52ChatLatest="gpt-5.2-chat-latest",I.GPT52Pro="gpt-5.2-pro",I.O1Pro="o1-pro",I.O1="o1",I.O1Mini="o1-mini",I.O3Pro="o3-pro",I.O3="o3",I.O3Mini="o3-mini",I.O4Mini="o4-mini",I))(Qt||{});var Xt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{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}],Hr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Du=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},$t=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ie()}),Kr=()=>structuredClone({...$t(),model:"gpt-5"}),Vr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),Wr=()=>({...$t(),model:"gpt-5-nano"}),Ls=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}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Lu(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=Du(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...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 Ae(a.message.refusal,e.model,e.id);let l=Ka(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 s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(p)throw new Ae(p,void 0,n);let f=Ka(h),x=d?.map(({id:A,index:T,function:{name:y,arguments:b}})=>{typeof A=="string"&&typeof T=="number"&&!s.indexIdMap[T]&&(s.indexIdMap[T]=A);let C=s.indexIdMap[T];return C?{id:C,type:"function",function:{name:y,params:b}}:null}).filter(A=>A!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,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)}}},Ka=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Lu(i){return i.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 Te=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Ls(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:s})}},Zt=class extends Te{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Xt,...s??[]];let a=c=>{let u=Ye({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!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 h=p?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[T,y]of f){let b=Math.abs(h-y);b<A&&(A=b,x=T)}g.thinkingTokenBudget=x}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...$t(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Gu=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},Uu=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Gs=$t,Va=Vr,Wa=Wr,Ja=Kr,en=class extends Te{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,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={...Gs(),...o},u=Gu(r),p=Uu(u);l=[...Xt,...l??[]];let d=g=>{let h=Ye({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:p&&(h?.supported?.structuredOutputs??!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:h?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Jr=class i{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.");Bu(e),this.services=[...e].sort(t?.comparator??i.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 i(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(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}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){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!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:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={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}}},t=0,n=0,r=0,o=0;for(let s of this.services){let a=s.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,o+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let s of this.services){let a=s.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,s=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=s}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,s=r?.requiresAudio,a=this.services,l=e.model;if((n||o||s)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||s&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),s&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Fe))throw p;switch(p.constructor){case yt:throw p;case We:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Ge:break;case At:break;case Qe:break;case st:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Fe)||r instanceof We&&![408,429,500,502,503,504].includes(r.status)||r instanceof yt)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let s=this.getNextService(this.services,n);if(!s.service)throw r;this.currentService=s.service,n=s.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Bu(i){let e=i.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<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.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 Nt(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.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 i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function Us(i,e){let t=i.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 Yr(i,e){return i.map(t=>{let n=t.getFeatures(),r=Us(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.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,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.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:s}}).sort((t,n)=>n.score-t.score)}function Qr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Nt(i),r=Yr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.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 Ya(i,e){let t=Nt(i),n=Yr(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,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Qa(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Xa(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var Qn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Qn||{}),Xn=(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))(Xn||{});var Xr=[{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 js=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ie()}),el=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),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,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 s=ju(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:s,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}}},tn=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...js(),...t},s=new Bs(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(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Xr,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 ju(i){return i.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=Za(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=Za(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 Za(i){return i?.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 Zn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Zn||{});var Zr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var qs=()=>structuredClone({model:"deepseek-chat",...ie()}),tl=()=>structuredClone({model:"deepseek-coder",...Se()}),nn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...qs(),...t};o=[...Zr,...o??[]],super({apiKey:e,config:s,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 er=(A=>(A.Gemini3Flash="gemini-3-flash-preview",A.Gemini3Pro="gemini-3-pro-preview",A.Gemini3ProImage="gemini-3-pro-image-preview",A.Gemini25Pro="gemini-2.5-pro",A.Gemini25Flash="gemini-2.5-flash",A.Gemini25FlashLite="gemini-2.5-flash-lite",A.Gemini20Flash="gemini-2.0-flash",A.Gemini20FlashLite="gemini-2.0-flash-lite",A.Gemini20ProExp="gemini-2.0-pro-exp-02-05",A.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",A.Gemini1Pro="gemini-1.0-pro",A.Gemini15Flash="gemini-1.5-flash",A.Gemini15Flash002="gemini-1.5-flash-002",A.Gemini15Flash8B="gemini-1.5-flash-8b",A.Gemini15Pro="gemini-1.5-pro",A.GeminiFlashLatest="gemini-flash-latest",A.GeminiFlashLiteLatest="gemini-flash-lite-latest",A.GeminiProLatest="gemini-pro-latest",A))(er||{}),eo=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(eo||{}),to=(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))(to||{}),no=(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))(no||{}),zs=(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))(zs||{}),nl=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var ro=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var oo=i=>{if(!i||typeof i!="object")return i;let e={...i};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,oo(n)]))),e.items&&(e.items=oo(e.items)),e},rl=[{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"}],Ks=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:rl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...ie()}),ol=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:rl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Se()}),Hs=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 x=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${A}`}let s=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<c.length;x++){let A=c[x];switch(A.role){case"user":{let T=Array.isArray(A.content)?A.content.map((y,b)=>{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: ${b})`)}}):[{text:A.content}];l.push({role:"user",parts:T});break}case"assistant":{let T=[],y=A.thoughtBlocks,b=A.functionCalls&&A.functionCalls.length>0,C=y?.[0],P=y?.map(v=>v.data).join("")??"",S=C?.signature;if(P&&T.push({...b?{}:{thought:!0},text:P,...S&&!b?{thought_signature:S}:{}}),A.functionCalls){let v=A.functionCalls.map((k,F)=>{let R;if(typeof k.function.params=="string"){let I=k.function.params;if(I.trim().length===0)R={};else try{R=JSON.parse(I)}catch{throw new Error(`Failed to parse function params JSON: ${I}`)}}else R=k.function.params;let w={functionCall:{name:k.function.name,args:R}};return S&&F===0&&(w.thought_signature=S),w});T.push(...v)}if(A.content&&T.push({text:A.content}),T.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:T});break}case"function":{let T=[],y=A,b=x;for(;;){if(!("functionId"in y))throw new Error(`Chat prompt functionId is empty (index: ${b})`);if(T.push({functionResponse:{name:y.functionId,response:{result:y.result}}}),b+1<c.length&&c[b+1].role==="function")b++,y=c[b];else break}x=b,l.push({role:"user",parts:T});break}default:throw new Error(`Invalid role: ${JSON.stringify(A)} (index: ${x})`)}}let u=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(A=>{let T={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},y=A.parameters?oo(A.parameters):void 0;return y===void 0||y&&typeof y=="object"&&Object.keys(y).length===0?y={...T}: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:[]}),{name:A.name,description:A.description,parameters:y}});u.push({function_declarations:x})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,A=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};u.push({google_maps:A})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.config.thinkingTokenBudgetLevels,A=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=x?.minimal??200,A&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=x?.low??800,A&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=x?.medium??5e3,A&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=x?.high??1e4,A&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=x?.highest??24500,A&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={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(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=oo(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new Ae("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new Ae("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new Ae("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new Ae("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new Ae("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new Ae("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new Ae("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new Ae("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new Ae("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){s.thought=c.text;let u=c.thoughtSignature||c.thought_signature;s.thoughtBlocks||(s.thoughtBlocks=[]),s.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else s.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!s.thoughtBlocks||s.thoughtBlocks.length===0)s.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=s.thoughtBlocks[s.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}s.functionCalls=[...s.functionCalls??[],{id:Ee(),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;s.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&&(s.citations=[...s.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return s});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});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}};supportsContextCache=e=>{let t=e;return nl.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:s}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!s||s.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),s&&s.length>0&&(a.contents=s);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let o=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${o}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:o=>{let s=o;if(s?.name)return{name:s.name,expiresAt:s.expireTime,tokenCount:s.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,o=e.modelConfig?.stream??this.config.stream,{dynamicContents:s,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:o?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=o?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={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"},u=this.config.safetySettings,p={contents:s,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if("cache"in s&&s.cache){r=o;break}}for(let o=0;o<e.length;o++){let s=e[o];if(s.role==="system"){t={role:"user",parts:[{text:s.content}]};continue}if(r>=0&&o<=r)if(s.role==="user"){let a=[];if(typeof s.content=="string")a.push({text:s.content});else if(Array.isArray(s.content))for(let l of s.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else s.role==="assistant"&&s.content&&n.push({role:"model",parts:[{text:s.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if(!("cache"in s&&s.cache))switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else if(r.role==="assistant"){let o=[];if(r.content&&o.push({text:r.content}),r.functionCalls)for(let s of r.functionCalls){let a;if(typeof s.function.params=="string")try{a=JSON.parse(s.function.params)}catch{a={}}else a=s.function.params??{};o.push({functionCall:{name:s.function.name,args:a}})}o.length>0&&n.push({role:"model",parts:o})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},rn=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,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 f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,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={...Ks(),...o},m=new Hs(d,c,r,e,s);l=[...ro,...l??[]];let g=f=>{let x=Ye({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,structuredOutputs:x?.supported?.structuredOutputs??!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:m.supportsContextCache(f),types:["persistent"]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let x=f,A=x?.config;if(!A)return f;let T={};A.maxTokens!==void 0&&(T.maxTokens=A.maxTokens),A.temperature!==void 0&&(T.temperature=A.temperature),A.topP!==void 0&&(T.topP=A.topP),A.topK!==void 0&&(T.topK=A.topK),A.presencePenalty!==void 0&&(T.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(T.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(T.stopSequences=A.stopSequences),A.endSequences!==void 0&&(T.endSequences=A.endSequences),A.stream!==void 0&&(T.stream=A.stream),A.n!==void 0&&(T.n=A.n);let y={...x};Object.keys(T).length>0&&(y.modelConfig={...x.modelConfig??{},...T});let b=A.thinking?.thinkingTokenBudget;if(typeof b=="number"){let C=d.thinkingTokenBudgetLevels,P=[["minimal",C?.minimal??200],["low",C?.low??800],["medium",C?.medium??5e3],["high",C?.high??1e4],["highest",C?.highest??24500]],S="minimal",v=Number.POSITIVE_INFINITY;for(let[k,F]of P){let R=Math.abs(b-F);R<v&&(v=R,S=k)}y.thinkingTokenBudget=S}return A.thinking?.includeThoughts!==void 0&&(y.showThoughts=!!A.thinking.includeThoughts),y});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:h??a})}};var qu=new Be,on=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(qu.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 tr=(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))(tr||{});var so=[{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 zu=()=>structuredClone({model:"llama-3.3-70b-versatile",...ie()}),sn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...zu(),...t},a={...n,streamingUsage:!1};o=[...so,...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:s,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 on(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var io=[];var ao=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(ao||{});var Ws=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ie()}),sl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),Vs=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:
|
|
170
170
|
${JSON.stringify(e.functions,null,2)}
|
|
171
171
|
`:"",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 p=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${p})`}).join(`
|
|
172
172
|
`);return c?`Assistant: ${l.content}
|
|
@@ -206,14 +206,14 @@ ${t.join(`
|
|
|
206
206
|
`)}`};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(`
|
|
207
207
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},gr=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,s;e.parameters?s=e.func.length===2?await e.func(r,o):await e.func(r):s=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??X.functionResultFormatter)(s);return{formatted:String(l),rawResult:s,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(s=>s.name===e.name);if(o||(o=this.funcList.find(s=>n(s.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(s){throw s instanceof dr?new mr(s.getFields(),o,e.id):s}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Eo=(i,e)=>{if(i.length===0)return[...e??[]];let t=i.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{Mo(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
|
|
208
208
|
${r.message}
|
|
209
|
-
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Fo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d})=>{let m=new gr(e),g=new Set,h=[],f=y=>{let b=
|
|
209
|
+
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Fo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d})=>{let m=new gr(e),g=new Set,h=[],f=y=>{let b=S=>S.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),C=b(y),P=e.find(S=>S.name===y);return P||(P=e.find(S=>b(S.name)===C)),P},x=t.map(y=>{if(!y.id)throw new Error(`Function ${y.name} did not return an ID`);let b=i.getOptions().tracer??X.tracer;return b?b.startActiveSpan(`Tool: ${y.name}`,async C=>{try{C?.setAttributes?.({"tool.name":y.name,"tool.mode":"native","function.id":y.id,"session.id":r??""});let{formatted:P,rawResult:S,parsedArgs:v}=await m.executeWithDetails(y,{sessionId:r,ai:i,functionResultFormatter:c,traceId:C?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(y.name.toLowerCase()),d?.includes(y.name.toLowerCase())){let k=f(y.name);k&&h.push({func:k,args:v,result:S})}if(a?C.addEvent("gen_ai.tool.message",{name:y.name}):C.addEvent("gen_ai.tool.message",{name:y.name,args:y.args,result:P??""}),s){let k={name:y.name};a||(k.args=y.args,k.result=P??""),s.addEvent("function.call",k)}return{result:P??"",role:"function",functionId:y.id,index:l}}catch(P){if(C?.recordException?.(P),P instanceof mr){let S=P.getFixingInstructions(),v={name:y.name,message:P.toString()};return a||(v.args=y.args,v.fixing_instructions=S),C?.addEvent?.("function.error",v),p&&Ms(P,l,S,u),{functionId:y.id,isError:!0,index:l,result:S,role:"function"}}throw P}finally{C?.end?.()}}):m.executeWithDetails(y,{sessionId:r,ai:i,functionResultFormatter:c,traceId:o,stopFunctionNames:d}).then(({formatted:C,rawResult:P,parsedArgs:S})=>{if(g.add(y.name.toLowerCase()),d?.includes(y.name.toLowerCase())){let v=f(y.name);v&&h.push({func:v,args:S,result:P})}if(s){let v={name:y.name};a||(v.args=y.args,v.result=C??""),s.addEvent("function.call",v)}return{result:C??"",role:"function",functionId:y.id,index:l}}).catch(C=>{if(!(C instanceof mr))throw C;let P=C.getFixingInstructions();if(s){let S={name:y.name,message:C.toString()};a||(S.args=y.args,S.fixing_instructions=P),s.addEvent("function.error",S)}return p&&Ms(C,l,P,u),{functionId:y.id,isError:!0,index:l,result:P,role:"function"}})}),T=(await Promise.all(x)).map(y=>y.result===void 0||y.result===""?{...y,result:"done"}:y);if(n.addFunctionResults(T,r),p){let y=T.filter(b=>!b.isError);y.length>0&&Aa(y,u)}if(h.length>0)throw new Dt(h);return g};function mi(i,e,t,n){if(!e||e.length===0)return;if(!i.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 Gl(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}function Xu(i){let e=0,t=!1,n=!1,r=!1,o=!1,s=[];for(let a=0;a<i.length;a++){let l=i[a];if(n){n=!1;continue}if(l==="\\"){n=!0;continue}if(l==='"'){t=!t;continue}t||(l==="{"?(s.push("{"),e++):l==="["?(s.push("["),e++):l==="}"?s.length>0&&s[s.length-1]==="{"&&(s.pop(),e--):l==="]"&&s.length>0&&s[s.length-1]==="["&&(s.pop(),e--))}if(s.length>0){let a=s[s.length-1];r=a==="[",o=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:o}}function Ul(i){if(!i.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(i),partialMarker:null}}catch{}let e=Xu(i),t=Zu(i);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Zu(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1)),e.match(/,\s*"[^"]*"\s*:\s*$/)?e=e.replace(/,\s*"[^"]*"\s*:\s*$/,""):e.match(/\{\s*"[^"]*"\s*:\s*$/)&&(e=e.replace(/"[^"]*"\s*:\s*$/,""));e.match(/[0-9][eE.+-]$/)||e.match(/[eE][+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r){r=!1;continue}if(s==="\\"){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"?t.push("}"):s==="["?t.push("]"):s==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():s==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}var Mt=Gn(Bl(),1),Hl=Gn(jl(),1),Kl=Gn(ql(),1),Vl=Gn(zl(),1);Mt.default.extend(Vl.default);Mt.default.extend(Kl.default);Mt.default.extend(Hl.default);function Wl(i,e,t=!1){try{return ep(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw El(i,e,r)}}function ep(i){if(!(0,Mt.default)(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Mt.default.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Jl(i,e,t=!1){try{return tp(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Fl(i,e,r)}}function tp(i){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=i.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",s=Mt.default.tz(n,o,r);if(!s.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return s.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 Yl=i=>(0,Mt.default)(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var yx=new Be,_o=(i,e)=>{let t=i.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";case"object":return typeof u=="object";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(i.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 '${i.name}' to be type '${c}' instead got '${e}'`);return}let o=c=>!(!c||typeof c!="object"||!("data"in c));if(i.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 '${i.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let u="data"in c,p="fileUri"in c;return!(!u&&!p||u&&p)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let u of e)if(!s(u)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(i.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 '${i.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 '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function hr(i){let e={};for(let t of i){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 s=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(s.push(c),l.add(c.url));r.citations=s}}}return Object.values(e)}var Ql=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
|
|
210
210
|
`),r=[];for(let o of n){let s=o.trim();if(s){if(s[0]&&e.has(s[0]))r.push(s.slice(1).trim());else if(t.test(s))r.push(s.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 Ci(i,e){let{index:t,delta:n,version:r}=e,o=i.find(a=>a.index===t)?.delta;if(!o)return i.push({index:t,delta:n,version:r}),i;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 s=i.find(a=>a.index===t);return s&&(s.version=r),i}var Ti=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)}},np=new Ti(500);function Xl(i,e,t=0,n=np){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let r=i.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 s=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}function Pt(i,e){if(typeof i!="string")throw pi(e,String(i),"URL must be a string");try{new URL(i)}catch{throw pi(e,i,"Invalid URL format. Expected a valid URL like https://example.com")}}function et(i,e){if(typeof i!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&i.length<t.minLength)throw Tn(e,i,"minLength",t.minLength);if(t.maxLength!==void 0&&i.length>t.maxLength)throw Tn(e,i,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(i))throw Tn(e,i,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw Tn(e,i,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(i)}catch{throw Tn(e,i,"format","valid URL")}}}function tt(i,e){if(typeof i!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&i<t.minimum)throw di(e,i,"minimum",t.minimum);if(t.maximum!==void 0&&i>t.maximum)throw di(e,i,"maximum",t.maximum)}}var Do=(i,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};vi(i,e,a,t,{strictMode:r,skipEarlyFail:s,treatAllFieldsOptional:o}),Si(i,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},Ri=(i,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 Ol(n)},vi=(i,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let s=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=s.map((g,h)=>({field:g,index:h})).filter(({index:g})=>!l.has(g)),u,p,d=-1,m=0;for(let{index:g,field:h}of c){let x=`${(t.extractedFields.length===0?"":`
|
|
211
211
|
`)+h.title}:`,A=Xl(n,x,t.s);if(A===-2||A===-3)return!0;if(A===-4)return t.inBlock=!0,!0;A>=0&&(d===-1||A<d)&&(d=A,m=x.length,u=g,p=h)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(h=>!h.isOptional);if(g)throw So(g)}break}if(a&&p&&a.name!==p.name)throw So(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,d).trim(),h=$o(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,p!==void 0&&u!==void 0&&(t.currField=p,t.currFieldIndex=u),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Si=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=i.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let g=`
|
|
212
212
|
${m.title}:`,h=n.indexOf(g,t.s);h!==-1&&h<c&&(c=h)}let p=n.substring(t.s,c).trim(),d=$o(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw So(p)}if(rp(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Ri(t,e,i.getOutputFields()):c||Ri(t,e,i.getOutputFields())}},rp=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let s=r[0];if(s){let a=`${s.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
|
|
213
213
|
${s.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=$o(s,d);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
|
|
214
|
-
`);for(let s of r){if(s.name in e)continue;let a=`${s.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 p=$o(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},Zl=(i,e,t=!1)=>{switch(i.type?.name){case"code":return wi(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(i.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(i.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Wl(i,e,t);case"datetime":return Jl(i,e,t);case"class":{let n=e;if(i.type.options&&!i.type.options.includes(n)){if(i.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${i.type.options.join(", ")}`)}return n}default:return e}};function*ec(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=p?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[s]:h}},r.streamedIndex[s]=u+g.length)}function*Oi(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*ec(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*ec(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function $o(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw Oo(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=wi(e);return t=JSON.parse(r),t}catch(r){throw kl(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Ql(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Ml(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=wi(s);s=JSON.parse(a)}catch{}t[r]=Zl(i,s,!0)}}else t=Zl(i,e)}catch(r){throw Pl(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&Pt(t,i),(n.name==="string"||n.name==="code")&&et(t,i),n.name==="number"&&tt(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?et(r,i):n.name==="number"&&tt(r,i));return t}function Lo(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw Oo(r);continue}let s=r.type;if(s){if(s.name==="url"&&Pt(o,r),(s.name==="string"||s.name==="code")&&et(o,r),s.name==="number"&&tt(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?Pt(a,r):s.name==="string"||s.name==="code"?et(a,r):s.name==="number"&&tt(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&No(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&No(r,a,t)}}}function No(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw Oo(s);continue}let l=s.type;if(l){if(l.name==="url"&&Pt(a,s),(l.name==="string"||l.name==="code")&&et(a,s),l.name==="number"&&tt(a,s),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?Pt(c,s):l.name==="string"||l.name==="code"?et(c,s):l.name==="number"&&tt(c,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&No(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&No(s,c,t)}}}var wi=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function ki(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});tc(r.field,t,s,n)}}async function Mi(i,e,t,n,r,o,s=!1){for(let a of i){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:s});tc(t.currField,n,u,o)}}var tc=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=op(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function op(i,e){let t=i.type?.name==="code",n=i.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*nc({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let p=u;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.thoughtBlocks||d.thoughtBlocks.length===0)&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*sp({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*ip({...r,state:c,debug:n});if(s){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());s.citations=c}if(e.push(s),n&&r.logger){let c=structuredClone(s);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*sp({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)Br(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:h,partialMarker:f}=Ul(s.content);if(h&&typeof h=="object"){let x={},A={};for(let T of Object.keys(h))if(d.some(y=>y.name===T)){let y=h[T],b=s.values[T];if(Array.isArray(y)&&y.length>0&&ap(y,f)&&(y=y.slice(0,-1)),A[T]=y,typeof y=="string"&&typeof b=="string"&&y.startsWith(b)){let C=y.slice(b.length);C&&(x[T]=C)}else Array.isArray(y)&&Array.isArray(b)?y.length>b.length&&(x[T]=y.slice(b.length)):JSON.stringify(y)!==JSON.stringify(b)&&(x[T]=y)}try{Lo(a,A,{allowMissingRequired:!0})}catch{}Object.assign(s.values,A),Object.keys(x).length>0&&(yield{index:i.index,delta:x});return}}if(vi(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await ii(u,s.xstate,s.content),l.length!==0&&await Mi(l,s.content,s.xstate,e,s.values,t),yield*Oi(a,s.content,s.values,s.xstate,i.index),await Co(p,s.values)}else i.thought&&i.thought.length>0?(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
215
|
-
Content: ${s.content}`)}async function*ip({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,signatureToolCallingManager:f,logger:x,debug:A,stopFunctionNames:T}){let y=f?void 0:mi(t,i.functionCalls,i.values,n);if(y){if(!r)throw new Error("Functions are not defined");let b=await Fo({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:x,debug:A,stopFunctionNames:T});i.functionsExecuted=new Set([...i.functionsExecuted,...b]),i.functionCalls=[]}else{let b=e.getOutputFields(),C=e.hasComplexFields(),P=!1;if(C)try{let
|
|
216
|
-
Content: ${F.content}`)}let
|
|
214
|
+
`);for(let s of r){if(s.name in e)continue;let a=`${s.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 p=$o(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},Zl=(i,e,t=!1)=>{switch(i.type?.name){case"code":return wi(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(i.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(i.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Wl(i,e,t);case"datetime":return Jl(i,e,t);case"class":{let n=e;if(i.type.options&&!i.type.options.includes(n)){if(i.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${i.type.options.join(", ")}`)}return n}default:return e}};function*ec(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=p?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[s]:h}},r.streamedIndex[s]=u+g.length)}function*Oi(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*ec(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*ec(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function $o(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw Oo(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=wi(e);return t=JSON.parse(r),t}catch(r){throw kl(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Ql(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Ml(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=wi(s);s=JSON.parse(a)}catch{}t[r]=Zl(i,s,!0)}}else t=Zl(i,e)}catch(r){throw Pl(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&Pt(t,i),(n.name==="string"||n.name==="code")&&et(t,i),n.name==="number"&&tt(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?et(r,i):n.name==="number"&&tt(r,i));return t}function Lo(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw Oo(r);continue}let s=r.type;if(s){if(s.name==="url"&&Pt(o,r),(s.name==="string"||s.name==="code")&&et(o,r),s.name==="number"&&tt(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?Pt(a,r):s.name==="string"||s.name==="code"?et(a,r):s.name==="number"&&tt(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&No(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&No(r,a,t)}}}function No(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw Oo(s);continue}let l=s.type;if(l){if(l.name==="url"&&Pt(a,s),(l.name==="string"||l.name==="code")&&et(a,s),l.name==="number"&&tt(a,s),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?Pt(c,s):l.name==="string"||l.name==="code"?et(c,s):l.name==="number"&&tt(c,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&No(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&No(s,c,t)}}}var wi=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function ki(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});tc(r.field,t,s,n)}}async function Mi(i,e,t,n,r,o,s=!1){for(let a of i){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:s});tc(t.currField,n,u,o)}}var tc=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=op(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function op(i,e){let t=i.type?.name==="code",n=i.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*nc({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let p=u;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.thoughtBlocks||d.thoughtBlocks.length===0)&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*sp({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*ip({...r,state:c,debug:n});if(s){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());s.citations=c}if(e.push(s),n&&r.logger){let c=structuredClone(s);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*sp({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)Br(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:h,partialMarker:f}=Ul(s.content);if(h&&typeof h=="object"){let x={},A={};for(let T of Object.keys(h))if(d.some(y=>y.name===T)){let y=h[T],b=s.values[T];if(Array.isArray(y)&&y.length>0&&ap(y,f)&&(y=y.slice(0,-1)),A[T]=y,typeof y=="string"&&typeof b=="string"&&y.startsWith(b)){let C=y.slice(b.length);C&&(x[T]=C)}else Array.isArray(y)&&Array.isArray(b)?y.length>b.length&&(x[T]=y.slice(b.length)):JSON.stringify(y)!==JSON.stringify(b)&&(Array.isArray(y)||(x[T]=y))}try{Lo(a,A,{allowMissingRequired:!0})}catch{}Object.assign(s.values,A),Object.keys(x).length>0&&(yield{index:i.index,delta:x});return}}if(vi(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await ii(u,s.xstate,s.content),l.length!==0&&await Mi(l,s.content,s.xstate,e,s.values,t),yield*Oi(a,s.content,s.values,s.xstate,i.index),await Co(p,s.values)}else i.thought&&i.thought.length>0?(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
215
|
+
Content: ${s.content}`)}async function*ip({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,signatureToolCallingManager:f,logger:x,debug:A,stopFunctionNames:T}){let y=f?void 0:mi(t,i.functionCalls,i.values,n);if(y){if(!r)throw new Error("Functions are not defined");let b=await Fo({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:x,debug:A,stopFunctionNames:T});i.functionsExecuted=new Set([...i.functionsExecuted,...b]),i.functionCalls=[]}else{let b=e.getOutputFields(),C=e.hasComplexFields(),P=!1;if(C)try{let S=JSON.parse(i.content),v={};for(let k of Object.keys(S))if(b.some(F=>F.name===k)){let F=S[k],R=i.values[k];if(typeof F=="string"&&typeof R=="string"&&F.startsWith(R)){let w=F.slice(R.length);w&&(v[k]=w)}else Array.isArray(F)&&Array.isArray(R)?F.length>R.length&&(v[k]=F.slice(R.length)):JSON.stringify(F)!==JSON.stringify(R)&&(Array.isArray(F)||(v[k]=F))}try{Lo(e,v,{allowMissingRequired:!0})}catch(k){let F=(k.message||"").toLowerCase();if(F.includes("at least")||F.includes("at most")||F.includes("must match pattern")||F.includes("invalid url")||F.includes("required")||F.includes("missing")||F.includes("valid email")||F.includes("number must be"))throw k}for(let k of Object.keys(S))b.some(F=>F.name===k)&&(i.values[k]=S[k]);yield{index:i.index,delta:v},P=!0}catch(S){let v=(S.message||"").toLowerCase();if(v.includes("at least")||v.includes("at most")||v.includes("must match pattern")||v.includes("invalid url")||v.includes("required")||v.includes("missing")||v.includes("valid email")||v.includes("number must be"))throw S}if(!P){let S=f!==void 0;Si(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:S,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(f){let S=await f.processResults(i.values);if(S&&S.length>0){if(!r)throw new Error("Functions are not defined");let v=await Fo({ai:t,functionList:r,functionCalls:S,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:x,debug:A,stopFunctionNames:T});i.functionsExecuted=new Set([...i.functionsExecuted,...v]),o.updateResult({name:void 0,content:i.content,functionCalls:S.map(k=>({id:k.id,type:"function",function:{name:k.name,params:k.args}})),index:i.index},s);return}}await ii(p,i.xstate,i.content,!0),await Co(d,i.values),m.length&&await ki(m,i.values,o,s),g.length!==0&&await Mi(g,i.content,i.xstate,o,i.values,s,!0),yield*Oi(e,i.content,i.values,i.xstate,i.index)}}async function*rc({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:f,debug:x,signatureToolCallingManager:A,stopFunctionNames:T,disableMemoryCleanup:y}){let b=e.results??[],C=A!==void 0;t.addResponse(b,n);let P=[];for(let F of b)if(Array.isArray(F?.citations))for(let R of F.citations)R?.url&&P.push({url:R.url,title:R.title,description:R.description,license:R.license,publicationDate:R.publicationDate,snippet:R.snippet});for(let F of b){let R=l[F.index];if(!R)throw new Error(`No state found for result (index: ${F.index})`);if(e.modelUsage){let w=Array.from(new Map(P.filter(_=>_.url).map(_=>[_.url,_])).values()),I={...e.modelUsage,...w.length?{citations:w}:{}};if(c.push(I),x&&f){let _=structuredClone(I);delete _.citations,f({name:"ChatResponseUsage",value:_}),I.citations&&I.citations.length>0&&f({name:"ChatResponseCitations",value:I.citations})}}if(A&&F.content){F.thought&&F.thought.length>0&&(R.values[m]=F.thought),Do(g,R.values,F.content,{strictMode:a,treatAllFieldsOptional:C});let I=(await A.processResults(R.values))?.map(_=>({id:_.id,type:"function",function:{name:_.name,params:_.args}}));I&&I.length>0&&t.updateResult({name:F.name,content:F.content,functionCalls:I,index:F.index},n)}if(F.functionCalls?.length){let w=mi(i,F.functionCalls,R.values);if(w&&w.length>0){if(!o)throw new Error("Functions are not defined");let I;try{I=await Fo({ai:i,functionList:o,functionCalls:w,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:u,index:F.index,functionResultFormatter:h,logger:f,debug:x,stopFunctionNames:T})}catch(_){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),_}R.functionsExecuted=new Set([...R.functionsExecuted,...I])}}else if(F.content){F.thought&&F.thought.length>0&&(R.values[m]=F.thought);let w=g.getOutputFields();if(g.hasComplexFields())try{let _=JSON.parse(F.content),M={};for(let O of Object.keys(_))w.some(E=>E.name===O)&&(M[O]=_[O]);Lo(g,M),Object.assign(R.values,M)}catch(_){let M=_ instanceof SyntaxError;if((_.name?.includes("ValidationError")||_.name?.includes("Error"))&&!M){let E=(_.message||"").toLowerCase();if(E.includes("at least")||E.includes("at most")||E.includes("must match pattern")||E.includes("invalid url")||E.includes("required")||E.includes("missing")||E.includes("valid email")||E.includes("number must be"))throw _}if(M)Do(g,R.values,F.content,{strictMode:a,treatAllFieldsOptional:C});else throw _}else Do(g,R.values,F.content,{strictMode:a,treatAllFieldsOptional:C})}if(await Co(p,R.values),y||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await ki(d,R.values,t,n),F.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
216
|
+
Content: ${F.content}`)}let S=l.map(F=>F.values);for(let F of S)for(let R of g.getOutputFields())R.isInternal&&delete F[R.name];let v=g.getOutputFields(),k=S.map((F,R)=>{let w={};for(let I of v)I.isInternal||(w[I.name]=F[I.name]);return F[m]!==void 0&&(w[m]=F[m]),{index:R,delta:w}});for(let F of k)yield F}function ap(i,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function oc(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[o,s]of t.entries()){let a=e?Array.from(e).some(p=>s.functionsExecuted.has(p)):!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(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var Cn=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 J=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Pi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new J("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 J("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 J('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 J(`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 J)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new J(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new J(`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 J(`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 J(`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 J("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new J("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(`
|
|
217
217
|
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new J(`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 J?r:new J(`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 J(`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 J?r:new J(`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 J(`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 J(`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(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof J?o:new J(`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 s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new J(`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 J(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new J(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(s==="audio"&&a)throw new J(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(s==="image")throw new J(`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(s==="audio")throw new J(`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(s){throw s instanceof J?s:new J(`Output field "${e}": ${s instanceof Error?s.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(X.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 s=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new J(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new J(`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 J(`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 J(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new J(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 J("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 J(`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 J(`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 s=this.input.slice(o,Math.min(this.position,o+20));throw new J(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${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 J(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function sc(i){return new Pi(i).parse()}var fr=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ei(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ei(s)])):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}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new be(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Oe=class i{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}cache(){return new i({...this,isCached:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},de=Object.assign(()=>new fr,{string:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),number:i=>new Oe({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),boolean:i=>new Oe({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),json:i=>new Oe({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),datetime:i=>new Oe({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),date:i=>new Oe({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),class:(i,e)=>new Oe({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:i=>new Oe({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),audio:i=>new Oe({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),file:i=>new Oe({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),url:i=>new Oe({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),email:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(i,e)=>new Oe({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1,isCached:!1}),object:(i,e)=>new Oe({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function Ei(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,Ei(t)])):void 0}}function Go(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var q=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},be=class i{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=sc(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 q(`Invalid Signature: ${n.message}`,void 0,r)}throw new q(`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 i)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),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new q("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 q("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 q?t:new q(`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 q("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 i(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new q("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 q("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 q("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);mt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new q(`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 q(`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 q?t:new q(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);mt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new q(`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 q(`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 q?t:new q(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new q("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 mt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new q("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 mt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`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 i(this);return n.addInputField({name:e,...Go(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...Go(t)},o=n.parseField(r);mt(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new q(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new q(`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 i(this);return n.addOutputField({name:e,...Go(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...Go(t)},o=n.parseField(r);mt(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new q(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new q(`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,this._hasComplexFields=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{mt(e,"input")}),this.getOutputFields().forEach(e=>{mt(e,"output")}),this.sigHash=Le("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ac(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{mt(e,"input")}),this.getOutputFields().forEach(e=>{mt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Le("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ac(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`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 q(`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 q(`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 q(`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 q("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new q("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return Po(e,this.description??"Schema")}};function ic(i){let e=i.name;return i.isOptional&&(e+="?"),i.isInternal&&(e+="!"),i.type&&(e+=`:${i.type.name}`,i.type.isArray&&(e+="[]"),i.type.name==="class"&&i.type.options&&(e+=` "${i.type.options.join(" | ")}"`)),i.description&&i.type?.name!=="class"&&(e+=` "${i.description}"`),e}function ac(i,e,t){let n=i?`"${i}" `:"",r=e.map(ic).join(", "),o=t.map(ic).join(", ");return`${n}${r} -> ${o}`}function lp(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function mt(i,e){if(!i.name||i.name.length===0)throw new q("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!lp(i.name))throw new q(`Invalid field name '${i.name}' - must be camelCase or snake_case`,i.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(X.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(i.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new q(`Field name '${i.name}' is too generic`,i.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(i.name.length<2)throw new q(`Field name '${i.name}' is too short`,i.name,"Field names must be at least 2 characters long");if(i.name.length>50)throw new q(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&cp(i,e)}function cp(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new q(`${t.name} type is not supported in output fields`,i.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new q("Class type is not supported in input fields",i.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new q("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new q("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new q(`Invalid class option "${o}"`,i.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 q("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new q("Arrays of code are not commonly supported",i.name,"Consider using a single code field or an array of strings instead");if(i.isInternal&&e==="input")throw new q("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&Fi(t.fields,i.name,e)}function Fi(i,e,t,n=1){for(let[r,o]of Object.entries(i)){let s=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new q(`${o.type} type is not allowed in nested object fields`,s,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&Fi(o.fields,s,t,n+1),o.isArray&&o.fields&&Fi(o.fields,`${s}[]`,t,n+1)}}var Et=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new be(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 Cn,this.key={id:this.signature.hash()}}getSignature(){return new be(this.signature)}setSignature(e){this.signature=new be(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(s=>{let a={};for(let l of o){let c=s[l.name];c!==void 0&&(_o(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 hr(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 lc=`
|
|
218
218
|
## Function Call Instructions
|
|
219
219
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
@@ -270,15 +270,15 @@ ${uc(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){return this.s
|
|
|
270
270
|
`),[])};render=(e,{examples:t,demos:n})=>{if(!this.examplesInSystem)return this.renderWithMessagePairs(e,{examples:t,demos:n});let r=t?[{type:"text",text:`
|
|
271
271
|
|
|
272
272
|
## Examples
|
|
273
|
-
`},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],s=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=s&&a,c=this.task.text;if(l){let d=[{type:"text",text:c},...r,...o];d.reduce(Lt(""),[]),d?.[0]&&(c=d[0].text)}let u={role:"system",content:c,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],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"){d.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");d.push({role:"assistant",content:f})}return[u,...d]}let p=this.renderSingleValueUserContent(e,r,o,l);return[u,{role:"user",content:p}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r=t&&t.length>0||n&&n.length>0,s={role:"system",content:r?this.task.text+pp:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],l=n?this.renderDemosAsMessages(n):[],c=[];for(let b of[...a,...l])c.push(b.userMessage),c.push(b.assistantMessage);let u=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||u==="after-examples";if(this.contextCache&&c.length>0&&p){let b=c.length-1,C=c[b];C?.role==="assistant"&&(c[b]={...C,cache:!0})}if(Array.isArray(e)){let b=[],C=e,P=!0;for(let
|
|
273
|
+
`},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],s=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=s&&a,c=this.task.text;if(l){let d=[{type:"text",text:c},...r,...o];d.reduce(Lt(""),[]),d?.[0]&&(c=d[0].text)}let u={role:"system",content:c,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],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"){d.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");d.push({role:"assistant",content:f})}return[u,...d]}let p=this.renderSingleValueUserContent(e,r,o,l);return[u,{role:"user",content:p}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r=t&&t.length>0||n&&n.length>0,s={role:"system",content:r?this.task.text+pp:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],l=n?this.renderDemosAsMessages(n):[],c=[];for(let b of[...a,...l])c.push(b.userMessage),c.push(b.assistantMessage);let u=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||u==="after-examples";if(this.contextCache&&c.length>0&&p){let b=c.length-1,C=c[b];C?.role==="assistant"&&(c[b]={...C,cache:!0})}if(Array.isArray(e)){let b=[],C=e,P=!0;for(let S of C){let v=this.renderInputFields(S.values),k=v.every(F=>F.type==="text")?v.map(F=>F.text).join(`
|
|
274
274
|
`):v.reduce(Lt(`
|
|
275
|
-
`),[]);if(
|
|
275
|
+
`),[]);if(S.role==="user"){P&&r&&(typeof k=="string"?k=Rn+k:k=[{type:"text",text:Rn},...k],P=!1),b.push({role:"user",content:k});continue}if(S.role!=="assistant")throw new Error("Invalid message role");if(typeof k!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");b.push({role:"assistant",content:k})}return[s,...c,...b]}let d=this.sig.getInputFields(),m=d.filter(b=>b.isCached),g=d.filter(b=>!b.isCached),h=m.length>0;if(this.contextCache&&h&&(this.ignoreBreakpoints||u!=="system"&&u!=="after-functions")&&g.length>0){let b=m.map(v=>this.renderInField(v,e,void 0)).filter(v=>v!==void 0).flat();b.filter(v=>v.type==="text").forEach(v=>{v.text=`${v.text}
|
|
276
276
|
`});let C=b.every(v=>v.type==="text")?b.map(v=>v.text).join(`
|
|
277
277
|
`):b.reduce(Lt(`
|
|
278
278
|
`),[]);r&&(typeof C=="string"?C=Rn+C:C=[{type:"text",text:Rn},...C]);let P=g.map(v=>this.renderInField(v,e,void 0)).filter(v=>v!==void 0).flat();P.filter(v=>v.type==="text").forEach(v=>{v.text=`${v.text}
|
|
279
|
-
`});let
|
|
279
|
+
`});let S=P.every(v=>v.type==="text")?P.map(v=>v.text).join(`
|
|
280
280
|
`):P.reduce(Lt(`
|
|
281
|
-
`),[]);return[s,...c,{role:"user",content:C,cache:!0},{role:"user",content:
|
|
281
|
+
`),[]);return[s,...c,{role:"user",content:C,cache:!0},{role:"user",content:S}]}let A=this.sortFieldsCachedFirst(d).map(b=>this.renderInField(b,e,void 0)).filter(b=>b!==void 0).flat();A.filter(b=>b.type==="text").forEach(b=>{b.text=`${b.text}
|
|
282
282
|
`});let T=A.every(b=>b.type==="text")?A.map(b=>b.text).join(`
|
|
283
283
|
`):A.reduce(Lt(`
|
|
284
284
|
`),[]);r&&(typeof T=="string"?T=Rn+T:T=[{type:"text",text:Rn},...T]);let y=h&&g.length===0&&this.contextCache;return[s,...c,{role:"user",content:T,...y?{cache:!0}:{}}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((s,a)=>{let l=a.title;return s[l]||(s[l]=[]),s[l].push(a),s},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([s,a])=>{if(a.length===1){let l=a[0];return l.type?.name==="object"||l.type?.isArray&&l.type.fields?{title:s,name:l.name,description:`${l.description}
|
|
@@ -305,12 +305,12 @@ ${m}
|
|
|
305
305
|
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
306
306
|
`))):n.push(t),[{type:"text",text:n.join("")}]}},Uo=i=>i.map(e=>`\`${e.title}\``).join(", "),cc=(i,e)=>i.map(n=>{let r=n.title,o=n.type?.name?pc(n.type):"string",s=n.isOptional?`This optional ${o} field may be omitted`:`A ${o} field`,a="";if(n.description){let l=wn(n.description);e&&(l=Bo(l,e)),a=` ${l}`}return`${r}: (${s})${a}`.trim()}).join(`
|
|
307
307
|
`),uc=(i,e)=>i.map(n=>{let r=n.title,o=n.type?.name?pc(n.type):"string",s=n.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,a="";if(n.description&&n.description.length>0){let l=n.type?.name==="class"?n.description:wn(n.description);e&&(l=Bo(l,e)),a=` ${l}`}return n.type?.options&&n.type.options.length>0&&(a.length>0&&(a+=". "),a+=`Allowed values: ${n.type.options.join(", ")}`),`${r}: (${s})${a}`.trim()}).join(`
|
|
308
|
-
`),dp=(i,e)=>{if(i.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return i.type?.name==="datetime"&&e instanceof Date?Yl(e):i.type?.name==="image"&&typeof e=="object"||i.type?.name==="audio"&&typeof e=="object"||i.type?.name==="file"&&typeof e=="object"||i.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},pc=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Lt(i){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=i+t.text:e.push(t)}else e.push(t);return e}}var mp=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function wn(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Bo(i,e){if(e.size===0)return i;let t=i,n=Array.from(e.keys()).sort((r,o)=>o.length-r.length);for(let r of n){let o=e.get(r),s=new RegExp(`\`${r}\``,"g");t=t.replace(s,`\`${o}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${o}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${o}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${o}]`);let u=new RegExp(`\\(${r}\\)`,"g");t=t.replace(u,`(${o})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${o}\``)}return t}function gp(i,e){let t=i.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 hp(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.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 jo(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?gp(t,n):!1)&&t){let l=hp(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 s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function dc(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await jo(r,t,i,e)}var qo=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}=fp(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,s=new Map;for(let[a,l]of this.tools.entries())s.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=s.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 Pe(`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[s,a]of Object.entries(r)){let l=[...o,s];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 s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}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 fp(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=xp(u);e.push({name:yp(d),title:Ap(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function xp(i){switch(i.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=i.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 Ap(i,e){return`${i} ${e.replace(/\./g," ")}`}function yp(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function hc(i,e,t){let n=new be(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=_i(o.name),l=gc(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:mc(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 i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=bp(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let s=_i(o.name),a=gc(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:mc(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function bp(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Ip(u),g={name:_i(d),title:Tp(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ip(i){switch(i.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=i.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 Tp(i,e){return`${i} ${e.replace(/\./g," ")}`}function _i(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function mc(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function gc(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var xr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new qo(e)}processSignature(e){let{signature:t}=hc(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 Ce=class i extends Et{clone=()=>new i(this.signature,this.options);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};this.promptTemplate=new(t?.promptTemplate??Gt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Eo(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return li()}getMergedCustomLabels(e,t){return _t(X.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){li(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} 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:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await dc(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}:{}},x=this.isDebug(e,n),A=a===0,T=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let y,b=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);y={type:"json_schema",schema:{name:"output",strict:!0,schema:Po(b)}}}let P=n?.contextCache?.cacheBreakpoint??"after-examples",O=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,v=n?.contextCache&&(O||P==="after-functions"||P==="after-examples"),M=o?.length&&v?o.map((R,w)=>({...R,cache:w===o.length-1})):o;return await e.chat({chatPrompt:h,functions:M,functionCall:s,modelConfig:f,model:c,responseFormat:y},{sessionId:l,rateLimiter:u,stream:p,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??X.abortSignal,stepIndex:a,logger:T,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,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,h=n.model,f=this.usage,x=r===0,A=this.isDebug(e,n),T=this.getLogger(e,n),{functions:y,functionCall:b}=Gl(u,d,x,n),C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:y,functionCall:b,stepIndex:r});C instanceof ReadableStream?yield*nc({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:y,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:T,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*rc({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:y,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(R=>R.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new bn,d=[...this.functions,...r.functions?Eo(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new xr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new xr(d));let h,f,x=this.options?.promptTemplate??Gt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,T={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:A};this.promptTemplate=new x(this.signature,T);let y,b=performance.now();Array.isArray(t)?(qa(t),y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let C=performance.now()-b,P=this.getMetricsInstruments(),O=this.getMergedCustomLabels(e,r);P&&vo(P,"prompt_render",C,this.getSignatureName(),O);let v=performance.now();p.addRequest(y,r.sessionId);let M=performance.now()-v;P&&vo(P,"memory_update",M,this.getSignatureName(),O);let F=new Map;n.forEach(R=>{F.set(R.index,{})});e:for(let R=0;R<u;R++){let w=c;for(let I=0;I<=w;I++)try{for(let k=0;k<c;k++){n.forEach(E=>{E.content="",E.values={},E.functionCalls=[],E.functionsExecuted=new Set,E.xstate={extractedFields:[],streamedIndex:{},s:-1}}),k>0&&F.forEach((E,$)=>{F.set($,{})});let S=new Map;n.forEach(E=>{S.set(E.index,{})});try{let E=this.forwardCore({options:r,ai:e,mem:p,stepIndex:R,span:o,traceContext:s,states:n,stopFunctionNames:l}),$=!1;try{for await(let U of E)if(U!==void 0){let H=U.index,W=U.delta,ue=S.get(H)??{},ae=F.get(H)??{},me={},le=!1;for(let oe of Object.keys(W)){let Re=W[oe],ye=ue[oe],ze;typeof Re=="string"&&(typeof ye=="string"||ye===void 0)?ze=(ye??"")+Re:Array.isArray(Re)&&(Array.isArray(ye)||ye===void 0)?ze=[...ye??[],...Re]:ze=Re,ue[oe]=ze;let xe=ze,ke=ae[oe];if(typeof xe=="string"&&typeof ke=="string")if(xe.startsWith(ke)){let V=xe.slice(ke.length);V&&(me[oe]=V,le=!0,ae[oe]=xe)}else ke.startsWith(xe)||xe!==ke&&(me[oe]=xe,le=!0,ae[oe]=xe);else if(Array.isArray(xe)&&Array.isArray(ke)){if(xe.length>ke.length){let V=xe.slice(ke.length);me[oe]=V,le=!0,ae[oe]=xe}}else JSON.stringify(xe)!==JSON.stringify(ke)&&(me[oe]=xe,le=!0,ae[oe]=xe)}le&&(yield{version:k,index:U.index,delta:me})}}catch(U){if(U instanceof Dt)$=!0;else throw U}if($?!1:oc(p,l,n,r?.sessionId)){let U=this.getMetricsInstruments();U&&wo(U,R+1,u,this.getSignatureName(),O);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let L=this.getMetricsInstruments();if(L){wo(L,R+1,u,this.getSignatureName(),O);let U=new Set;n.forEach(H=>{H.functionsExecuted.forEach(W=>U.add(W))}),U.size>0&&Cl(L,!0,U.size,!0,!1,this.getSignatureName(),O),Rl(L,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),O)}return}catch(E){f=E;let $,N=this.isDebug(e,r),L=this.getLogger(e,r),U=this.getMetricsInstruments(),H=this.getSignatureName(),W={error:E,errCount:k,logger:L,metricsInstruments:U,signatureName:H,span:o,debug:N,customLabels:O};if(o?.recordException(E),E instanceof Pe)$=_l(W),h=E;else if(E instanceof dt)$=$l(W),h=E;else if(E instanceof Ae)Nl(W);else if(!(E instanceof Qe)){let ue=E,ae=ue instanceof We&&ue.status>=500&&ue.status<600,me=ue instanceof Ge,le=ue instanceof st;throw ae||me||le?E:$i(E,e,this.signature)}if($&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields($)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let ae of n)ae.content="",ae.values={},ae.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let _=this.getMetricsInstruments();throw _&&ui(_,c,!1,c,this.getSignatureName(),O),$i(new Error(`Unable to fix validation error: ${(h??f)?.message??(h??f)?.toString()??"unknown error"}
|
|
308
|
+
`),dp=(i,e)=>{if(i.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return i.type?.name==="datetime"&&e instanceof Date?Yl(e):i.type?.name==="image"&&typeof e=="object"||i.type?.name==="audio"&&typeof e=="object"||i.type?.name==="file"&&typeof e=="object"||i.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},pc=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Lt(i){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=i+t.text:e.push(t)}else e.push(t);return e}}var mp=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function wn(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Bo(i,e){if(e.size===0)return i;let t=i,n=Array.from(e.keys()).sort((r,o)=>o.length-r.length);for(let r of n){let o=e.get(r),s=new RegExp(`\`${r}\``,"g");t=t.replace(s,`\`${o}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${o}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${o}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${o}]`);let u=new RegExp(`\\(${r}\\)`,"g");t=t.replace(u,`(${o})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${o}\``)}return t}function gp(i,e){let t=i.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 hp(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.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 jo(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?gp(t,n):!1)&&t){let l=hp(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 s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function dc(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await jo(r,t,i,e)}var qo=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}=fp(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,s=new Map;for(let[a,l]of this.tools.entries())s.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=s.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 Pe(`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[s,a]of Object.entries(r)){let l=[...o,s];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 s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}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 fp(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=xp(u);e.push({name:yp(d),title:Ap(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function xp(i){switch(i.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=i.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 Ap(i,e){return`${i} ${e.replace(/\./g," ")}`}function yp(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function hc(i,e,t){let n=new be(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=_i(o.name),l=gc(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:mc(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 i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=bp(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let s=_i(o.name),a=gc(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:mc(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function bp(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Ip(u),g={name:_i(d),title:Tp(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ip(i){switch(i.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=i.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 Tp(i,e){return`${i} ${e.replace(/\./g," ")}`}function _i(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function mc(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function gc(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var xr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new qo(e)}processSignature(e){let{signature:t}=hc(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 Ce=class i extends Et{clone=()=>new i(this.signature,this.options);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};this.promptTemplate=new(t?.promptTemplate??Gt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Eo(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return li()}getMergedCustomLabels(e,t){return _t(X.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){li(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} 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:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await dc(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}:{}},x=this.isDebug(e,n),A=a===0,T=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let y,b=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);y={type:"json_schema",schema:{name:"output",strict:!0,schema:Po(b)}}}let P=n?.contextCache?.cacheBreakpoint??"after-examples",S=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,v=n?.contextCache&&(S||P==="after-functions"||P==="after-examples"),k=o?.length&&v?o.map((R,w)=>({...R,cache:w===o.length-1})):o;return await e.chat({chatPrompt:h,functions:k,functionCall:s,modelConfig:f,model:c,responseFormat:y},{sessionId:l,rateLimiter:u,stream:p,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??X.abortSignal,stepIndex:a,logger:T,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,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,h=n.model,f=this.usage,x=r===0,A=this.isDebug(e,n),T=this.getLogger(e,n),{functions:y,functionCall:b}=Gl(u,d,x,n),C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:y,functionCall:b,stepIndex:r});C instanceof ReadableStream?yield*nc({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:y,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:T,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*rc({ai:e,model:h,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:y,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(R=>R.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new bn,d=[...this.functions,...r.functions?Eo(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new xr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new xr(d));let h,f,x=this.options?.promptTemplate??Gt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,T={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:A};this.promptTemplate=new x(this.signature,T);let y,b=performance.now();Array.isArray(t)?(qa(t),y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let C=performance.now()-b,P=this.getMetricsInstruments(),S=this.getMergedCustomLabels(e,r);P&&vo(P,"prompt_render",C,this.getSignatureName(),S);let v=performance.now();p.addRequest(y,r.sessionId);let k=performance.now()-v;P&&vo(P,"memory_update",k,this.getSignatureName(),S);let F=new Map;n.forEach(R=>{F.set(R.index,{})});e:for(let R=0;R<u;R++){let w=c;for(let I=0;I<=w;I++)try{for(let M=0;M<c;M++){n.forEach(E=>{E.content="",E.values={},E.functionCalls=[],E.functionsExecuted=new Set,E.xstate={extractedFields:[],streamedIndex:{},s:-1}}),M>0&&F.forEach((E,$)=>{F.set($,{})});let O=new Map;n.forEach(E=>{O.set(E.index,{})});try{let E=this.forwardCore({options:r,ai:e,mem:p,stepIndex:R,span:o,traceContext:s,states:n,stopFunctionNames:l}),$=!1;try{for await(let U of E)if(U!==void 0){let H=U.index,W=U.delta,ue=O.get(H)??{},ae=F.get(H)??{},me={},le=!1;for(let oe of Object.keys(W)){let Re=W[oe],ye=ue[oe],ze;typeof Re=="string"&&(typeof ye=="string"||ye===void 0)?ze=(ye??"")+Re:Array.isArray(Re)&&(Array.isArray(ye)||ye===void 0)?ze=[...ye??[],...Re]:ze=Re,ue[oe]=ze;let xe=ze,ke=ae[oe];if(typeof xe=="string"&&typeof ke=="string")if(xe.startsWith(ke)){let V=xe.slice(ke.length);V&&(me[oe]=V,le=!0,ae[oe]=xe)}else ke.startsWith(xe)||xe!==ke&&(me[oe]=xe,le=!0,ae[oe]=xe);else if(Array.isArray(xe)&&Array.isArray(ke)){if(xe.length>ke.length){let V=xe.slice(ke.length);me[oe]=V,le=!0,ae[oe]=xe}}else JSON.stringify(xe)!==JSON.stringify(ke)&&(me[oe]=xe,le=!0,ae[oe]=xe)}le&&(yield{version:M,index:U.index,delta:me})}}catch(U){if(U instanceof Dt)$=!0;else throw U}if($?!1:oc(p,l,n,r?.sessionId)){let U=this.getMetricsInstruments();U&&wo(U,R+1,u,this.getSignatureName(),S);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let L=this.getMetricsInstruments();if(L){wo(L,R+1,u,this.getSignatureName(),S);let U=new Set;n.forEach(H=>{H.functionsExecuted.forEach(W=>U.add(W))}),U.size>0&&Cl(L,!0,U.size,!0,!1,this.getSignatureName(),S),Rl(L,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),S)}return}catch(E){f=E;let $,N=this.isDebug(e,r),L=this.getLogger(e,r),U=this.getMetricsInstruments(),H=this.getSignatureName(),W={error:E,errCount:M,logger:L,metricsInstruments:U,signatureName:H,span:o,debug:N,customLabels:S};if(o?.recordException(E),E instanceof Pe)$=_l(W),h=E;else if(E instanceof dt)$=$l(W),h=E;else if(E instanceof Ae)Nl(W);else if(!(E instanceof Qe)){let ue=E,ae=ue instanceof We&&ue.status>=500&&ue.status<600,me=ue instanceof Ge,le=ue instanceof st;throw ae||me||le?E:$i(E,e,this.signature)}if($&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields($)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let ae of n)ae.content="",ae.values={},ae.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let _=this.getMetricsInstruments();throw _&&ui(_,c,!1,c,this.getSignatureName(),S),$i(new Error(`Unable to fix validation error: ${(h??f)?.message??(h??f)?.toString()??"unknown error"}
|
|
309
309
|
|
|
310
310
|
LLM Output:
|
|
311
|
-
${n.map(
|
|
311
|
+
${n.map(M=>M.content).join(`
|
|
312
312
|
---
|
|
313
|
-
`)}`),e,this.signature)}catch(_){let
|
|
313
|
+
`)}`),e,this.signature)}catch(_){let M=_,O=M instanceof We&&M.status>=500&&M.status<600,E=M instanceof Ge,$=M instanceof st,N=M instanceof Qe;if((O||E||$||N)&&I<w){let U=this.isDebug(e,r),H=this.getLogger(e,r),ae=Math.min(6e4,1e3*Math.pow(2,I));U&&H&&H({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${I+1}/${w+1}): ${M.message}. Retrying in ${ae}ms...`}),o?.addEvent("infrastructure.retry",{attempt:I+1,maxRetries:w,delay:ae,errorType:M instanceof We?"status_error":M instanceof Ge?"network_error":M instanceof st?"timeout_error":"stream_terminated",errorMessage:M.message}),await new Promise(me=>setTimeout(me,ae));continue}throw _}}throw P&&wo(P,u,u,this.getSignatureName(),S),$i(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&&Pt(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&et(r,n),o.name==="number"&&tt(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let s=0;s<r.length;s++){let a=r[s];o.name==="string"||o.name==="code"?et(a,n):o.name==="number"?tt(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${s}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let s=e[r];if(o.isOptional&&s===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?et(s,a):o.type==="number"?tt(s,a):o.type==="object"&&o.fields&&typeof s=="object"&&s!==null&&this.validateObjectFields(s,o.fields,a.name),o.isArray&&Array.isArray(s))for(let l=0;l<s.length;l++){let c=s[l];o.type==="string"||o.type==="code"?et(c,a):o.type==="number"?tt(c,a):o.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(A=>"role"in A))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments(),l=this.getMergedCustomLabels(e,n);a&&vo(a,"state_creation",s,this.getSignatureName(),l);let c=n?.tracer??this.options?.tracer??e.getOptions().tracer,u=this.functions;if(n?.functions&&(u=Eo(n.functions,this.functions)),!c){yield*this._forward2(e,t,o,{...n,functions:u});return}let p=u?.map(A=>A.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...p?{provided_functions:p}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},m=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,g=m?`AxGen > ${m}`:"AxGen",h=c.startSpan(g,{kind:je.SERVER,attributes:d}),f=St.active(),x=Hn.setSpan(f,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:u},h,x),!this.excludeContentFromTrace){let A=o.map(y=>y.values),T=A.length===1?A[0]:A;h.addEvent("output",{content:JSON.stringify(T,null,2)})}}finally{h.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??X.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&o){let d=await r(o);if(d!==void 0)return d}let s=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,p=!1;try{let d=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);d&&Sl(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let g=this._forward1(e,t,n??{}),h=[],f=0,x=0;for await(let S of g)S.version!==f&&(h=[]),f=S.version,h=Ci(h,S),x++;u=f;let A=performance.now();p=!!n?.resultPicker;let T=await jo(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-A,C=h[T]?.delta??{},P=Array.isArray(t)?{}:t??{};if(this.trace={...P,...C},p&&this.isDebug(e,n)){let S=this.getLogger(e,n);Ra(h.length,T,y,S)}if(c=!0,d&&(vl(d,h.length,p,p?y:void 0,a,m),wl(d,l,x,void 0,a,m)),r&&o)try{await r(o,C)}catch{}return C}catch(d){throw c=!1,d}finally{let d=performance.now()-s,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(Il(m,d,c,a,e.getName(),n?.model?String(n.model):void 0,g),u>0&&ui(m,u,c,n?.maxRetries??10,a,g))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??X.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&o){let p;try{p=await r(o)}catch{}if(p!==void 0){yield{version:0,index:0,delta:p};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let s=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let p of s)p.version!==l&&(a=[]),l=p.version,a=Ci(a,p);let c=await jo(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??X.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??X.logger??e.getLogger()}computeCacheKey(e,t){let n=Le("sha256");n.update(this.signature.hash()??"");let r=o=>{let s=typeof o;if(n.update(`|${s}|`),o==null){n.update("null");return}if(s==="string"||s==="number"||s==="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=Le("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 s=t.map(a=>o.values?.[a]);for(let a of s)r(a)}else{let o=t.map(s=>e?.[s]);for(let s of o)r(s)}return n.digest("hex")}},Ar=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function $i(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let s=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:s,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Ar(`Generate failed: ${n.message}`,l,{cause:n})}var Cp=i=>i.replace(/^\W+|\W+$/g,""),Rp=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},wp=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},vp=i=>{let e=i.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}},Sp=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Op=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},zo={trimNonAlphaNum:Cp,splitIntoTwo:Rp,dedup:wp,extractIdAndText:vp,extractIndexPrefixedText:Sp,batchArray:Op};var Ho=class extends Ce{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."
|
|
314
314
|
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}=zo.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 Ko=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 FA=new Be,Vo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Wo=class{ai;db;debug;constructor(e){this.db=new kt,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 s=o.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var fc=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 xc(i,e){return i.filter(t=>!e.has(t))}function Ac(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function Ut(i){let e=i.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function kp(i,e){return Ut(i)===Ut(e)?1:0}function Mp(i,e){let t=Ut(i).split(" "),n=Ut(e).split(" "),r=Ac(t),o=Ac(n),s=0;for(let c in r){let u=r[c]??0,p=o[c]??0;s+=Math.min(u,p)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function Pp(i,e,t,n=!1){let r=Ut(i).split(" "),o=Ut(e).split(" "),s=Ut(t).split(" "),a=new Set([...fc,...r]);o=xc(o,a),s=xc(s,a);let l=0,c=l/o.length,u=l/s.length,p=2*c*u/(c+u);return n?u:p}var yc={emScore:kp,f1Score:Mp,novelF1ScoreOptimized:Pp};var Jo=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 s=0;s<n;s++){let a=this.examples[s];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 ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
|
|
315
315
|
Performance: `,r,"/",n,"Average Score: ",o,`
|
|
316
316
|
`)}};function Yo(i){return i.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
|
|
@@ -442,7 +442,7 @@ Score: ${t.value.score.toFixed(3)}
|
|
|
442
442
|
Config: ${JSON.stringify(t.value.config)}
|
|
443
443
|
${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
|
|
444
444
|
${JSON.stringify(t)}
|
|
445
|
-
${e}`}i(n)}},yr=Ni();var Di={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Qo,_p=i=>{if(Qo)return Qo;if(i)return Qo=$p(i),Qo};var Xo=Di,Cc=i=>{Xo={...Xo,...i}},Rc=()=>({...Xo}),$p=i=>({optimizationLatencyHistogram:i.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:i.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:i.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:i.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:i.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:i.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:i.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:i.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:i.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:i.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:i.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:i.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:i.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:i.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:i.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:i.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:i.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:i.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:i.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:i.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:i.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:i.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:i.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:i.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:i.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:i.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:i.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:i.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:i.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:i.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:i.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ut=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Xo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Np=(i,e,t,n,r,o)=>{try{let s=ut({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,s),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,s),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record optimization metric:",s)}},Dp=(i,e,t,n,r,o,s)=>{try{let a=ut({optimizer_type:o,...s});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},Lp=(i,e,t,n)=>{try{let r=ut({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},Gp=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:n,...o});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,s),i.costUsageCounter&&i.costUsageCounter.add(t,s),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,s)}catch(s){console.warn("Failed to record resource usage metric:",s)}},Up=(i,e,t,n)=>{try{let r=ut({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},Bp=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,o),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,o),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},jp=(i,e,t,n,r,o)=>{try{let s=ut({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,s),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,s)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,s),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,s))}catch(s){console.warn("Failed to record checkpoint metric:",s)}},qp=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:n,...o});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,s),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,s),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,s),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,s)}catch(s){console.warn("Failed to record Pareto metric:",s)}},zp=(i,e,t,n,r,o,s)=>{try{let a=ut({optimizer_type:o,...s});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Hp=(i,e,t,n,r)=>{try{let o=ut({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Kp=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,o),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,o),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},gt=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)}},br=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}},qe=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 br({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=_p(X.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?yr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return _t(X.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a,r);let l,c=(g,h,f,x,A,T,y,b={},C)=>{this.getOptimizerLogger(C)?.({name:"RoundProgress",value:{round:g,totalRounds:C?.maxIterations??0,currentScore:h,bestScore:T,configuration:f}}),this.updateOptimizationProgress(g,h,f,x,A,T,y,b,C)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},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,s,a,r),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,s=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(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);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 s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),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:h})=>{let f=await n({prediction:g,example:h}),x=0;for(let[A,T]of Object.entries(f))x+=T*(d[A]||0);return x};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: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 s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[u]||0,f=0;for(let[x,A]of Object.entries(g))x!==u&&A<.3&&(f+=(.3-A)*2);return h-f};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 s of e)o[s]=s===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 s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Ce(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],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[h,f]of Object.entries(g))c[h]||(c[h]=[]),c[h].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=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)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||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,s=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;s+=u*(p-l),l=Math.max(l,p)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.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,s)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown",t)}return s}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,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,s=(t.match(/output:/g)||[]).length;zp(this.metricsInstruments,o,s,0,0,e,r)}Kp(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);Np(this.metricsInstruments,e,t,n,r,s),Up(this.metricsInstruments,e,n,s);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;Gp(this.metricsInstruments,l,a,n,void 0,s)}recordConvergenceMetrics(e,t,n,r,o,s){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(s);Dp(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);Lp(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Bp(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);jp(this.metricsInstruments,e,t,n,r,s)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);qp(this.metricsInstruments,e,t,n,r,s)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Hp(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??X.optimizerLogger??yr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=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: ${s.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 s=this.getOptimizerLogger(r);s&&s(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 wc(i){return be.create(i)}function $e(i,e){let t=typeof i=="string"?be.create(i):i;return new Ce(t,e)}function vc(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function ht(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(vc(i[s].scores,i[n].scores,e)){o=!0;break}vc(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function nt(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-s,0);o+=l*u,s=Math.max(s,c)}return o}function Bt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function Zo(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s: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(i,e){let t=new Set;for(let u of i)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,s=(u,p)=>{for(let d of i){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(s(u,p)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function Tr(i,e,t){let n=Ir(i,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 s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var On=class i extends qe{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;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";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 s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s: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??5)),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 s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(S,E)=>{try{e.setInstruction?.(S);let $=await e.forward(this.studentAI,E,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:$,example:E})||{}}catch{return{}}},p=async(S,E)=>{let $=[];for(let N of E)$.push(await u(S,N));return Zo($)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=S=>{let E=r?.paretoMetricKey,$=r?.paretoScalarize;if(typeof $=="function")return $(S);if(E)return Number.isFinite(S[E])?S[E]:0;let N=Object.values(S);return N.length?N.reduce((L,U)=>L+U,0)/N.length:0},h=[],f=async(S,E)=>{let $=[];for(let N of E){let L=await u(S,N);$.push(g(L))}return $};h.push(await f(d,l));let x=()=>{let S=h[0]?.length??0,E=[];for(let N=0;N<S;N++){let L=Number.NEGATIVE_INFINITY,U=new Set;for(let H=0;H<h.length;H++){let W=h[H][N];W>L+this.tieEpsilon?(L=W,U.clear(),U.add(H)):Math.abs(W-L)<=this.tieEpsilon&&U.add(H)}E.push(U)}let $=h.map(N=>Bt(N));return Tr(E,$)},A=r?.maxMetricCalls;if(!Number.isFinite(A)||A<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let T=Math.floor(A),y=this.getOptimizerLogger(r),b=r?.verbose??this.verbose?S=>console.log(`[GEPA] ${S}`):S=>{};y?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),b(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${T}`);let C=0,P=ht(m.map((S,E)=>({idx:E,scores:S.scores})),this.tieEpsilon).map(S=>S.idx),O;for(let S=0;S<this.numTrials&&!(T!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(T)));S++){let E=h[0]?.length??0,$=[];for(let B=0;B<E;B++){let z=Number.NEGATIVE_INFINITY,Z=new Set;for(let re=0;re<h.length;re++){let G=h[re][B];G>z+this.tieEpsilon?(z=G,Z.clear(),Z.add(re)):Math.abs(G-z)<=this.tieEpsilon&&Z.add(re)}$.push(Z)}let N=h.map(B=>Bt(B));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let B=D=>{let K=[],ee=D;for(;ee!==void 0;)K.push(ee),ee=m[ee]?.parent;return K},z=D=>D.length?D[Math.floor(this.rand()*D.length)]:void 0,Z=Ir($,N),re=new Set;for(let D of Z)for(let K of D)re.add(K);let G=Array.from(re),j;for(let D=0;D<10&&!j&&!(G.length<2);D++){let K=z(G),ee=z(G);if(K===ee)continue;ee<K&&([K,ee]=[ee,K]);let fe=new Set(B(K)),te=new Set(B(ee));if(fe.has(ee)||te.has(K))continue;let se=[...fe].filter(Me=>te.has(Me));if(se.length===0)continue;let ce=se.map(Me=>Math.max(1e-9,N[Me])),ge=this.rand()*ce.reduce((Me,Je)=>Me+Je,0),ve=se[se.length-1];for(let Me=0;Me<se.length;Me++){if(ge<ce[Me]){ve=se[Me];break}ge-=ce[Me]}j={i:K,j:ee,a:ve}}if(this.lastIterFoundNewProgram=!1,j){let{i:D,j:K,a:ee}=j,fe=N[ee],te=N[D],se=N[K],ce=m[ee].instruction,ge=m[D].instruction,ve=m[K].instruction,Me=ge===ce&&ve!==ge||ve===ce&&ge!==ve,Je=fe<=Math.min(te,se)&&Me,Ne="",He="i",he=!1;if(Je){let ft=`${D}|${K}|${ee}`;if(this.mergeAttemptKeys.has(ft))Je=!1;else{ge===ce&&ve!==ge?(Ne=ve,He="j"):ve===ce&&ge!==ve?(Ne=ge,He="i"):ge!==ce&&ve!==ce&&ge!==ve?te>se||te===se&&this.rand()<.5?(Ne=ge,He="i"):(Ne=ve,He="j"):(Ne=ge,He="i");let Tt=`${Math.min(D,K)}|${Math.max(D,K)}|${He}`;if(this.mergeCompositionKeys.has(Tt))Je=!1;else{this.mergeAttemptKeys.add(ft),this.mergeCompositionKeys.add(Tt);let rt=h[D],Ct=h[K],Rt=Array.from({length:rt.length},(pe,De)=>De),xt=Rt.filter(pe=>(rt[pe]??0)>(Ct[pe]??0)),wt=Rt.filter(pe=>(Ct[pe]??0)>(rt[pe]??0)),Ft=Rt.filter(pe=>!(xt.includes(pe)||wt.includes(pe))),Y=5,Ie=Math.ceil(Y/3),pt=(pe,De)=>{if(De<=0||pe.length===0)return[];if(pe.length<=De)return[...pe];let Ln=[],Mr=new Set;for(;Ln.length<De;){let ot=Math.floor(this.rand()*pe.length);Mr.has(ot)||(Mr.add(ot),Ln.push(pe[ot]))}return Ln},Ke=[];Ke.push(...pt(xt,Math.min(Ie,xt.length))),Ke.push(...pt(wt,Math.min(Ie,wt.length)));let Ve=Y-Ke.length;Ke.push(...pt(Ft,Math.max(0,Ve)));let kr=Y-Ke.length;if(kr>0){let pe=Rt.filter(De=>!Ke.includes(De));Ke.push(...pt(pe,Math.min(kr,pe.length)))}let gs=Ke.slice(0,Math.min(Y,Rt.length)),Hc=gs.map(pe=>l[pe]);he=!0;let Kc=(await f(Ne,Hc)).reduce((pe,De)=>pe+De,0),Vc=gs.reduce((pe,De)=>pe+(rt[De]??0),0),Wc=gs.reduce((pe,De)=>pe+(Ct[De]??0),0);if(Kc>=Math.max(Vc,Wc)+this.tieEpsilon){b(`Iteration ${S+1}: Merge accepted (programs ${D} + ${K} via ancestor ${ee})`);let pe=await p(Ne,l);m.push({instruction:Ne,parent:ee,scores:pe}),h.push(await f(Ne,l));let De=P.length,Ln=nt(P.map(ot=>m[ot].scores))??0;P=ht(m.map((ot,Jc)=>({idx:Jc,scores:ot.scores})),this.tieEpsilon).map(ot=>ot.idx);let Mr=nt(P.map(ot=>m[ot].scores))??0;(P.length>De||Mr>Ln+1e-6)&&(C=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(he)continue}}let L=Tr($,N,()=>this.rand()),U=this.minibatch?this.nextMinibatchIndices(c.length,S).map(B=>c[B]):c;if(r?.skipPerfectScore??!0){let B=Number(r?.perfectScore??1),z=await f(m[L].instruction,U);if(z.length>0&&z.every(Z=>Z>=B))continue}let H=!1,W=m[L].instruction,ue="reflective_mutation",ae,me;if(H){let B=(L+1)%m.length;W=await this.mergeInstructions(m[L].instruction,m[B].instruction,r),ue="merge",this.mergesUsed+=1}else{let B=r?.gepaAdapter;if(B){try{let z={instruction:m[L].instruction},Z=await B.evaluate(U,z,!0);ae=Array.isArray(Z?.scores)?Z.scores.reduce((D,K)=>D+(Number(K)||0),0):void 0;let re=B.make_reflective_dataset(z,Z,["instruction"]),G=await B.propose_new_texts?.(z,re,["instruction"]),j=G?.instruction??(G?Object.values(G)[0]:void 0);typeof j=="string"&&j.length>0?W=j:W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:D,example:K})=>{let ee=await n({prediction:D,example:K}),fe=Object.values(ee||{});return fe.length?fe.reduce((te,se)=>te+se,0)/fe.length:0},r)}catch{W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)}if(ae!==void 0)try{let z=await B.evaluate(U,{instruction:W},!1);me=Array.isArray(z?.scores)?z.scores.reduce((Z,re)=>Z+(Number(re)||0),0):void 0}catch{}}else W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)}let le=await f(m[L].instruction,U),oe=await f(W,U),Re=le.reduce((B,z)=>B+z,0),ye=oe.reduce((B,z)=>B+z,0);if(this.currentRound=S+1,await this.updateOptimizationProgress(this.currentRound,ye,{instructionLen:W.length,parent:L,totalRounds:this.numTrials},"GEPA",{strategy:ue,paretoSetSize:l.length},ye,{instructionLen:m[L].instruction.length,idx:L},{...r??{},maxIterations:this.numTrials}),!(ye>Re+this.tieEpsilon&&(ae===void 0||me===void 0||me>ae+this.tieEpsilon))){if(b(`Iteration ${S+1}: Rejected (child=${ye.toFixed(3)} <= parent=${Re.toFixed(3)})`),++C>=this.earlyStoppingTrials){b(`Early stopping: ${C} iterations without improvement`);break}continue}b(`Iteration ${S+1}: Accepted (child=${ye.toFixed(3)} > parent=${Re.toFixed(3)})`);let xe=await p(W,l);m.push({instruction:W,parent:L,scores:xe}),h.push(await f(W,l));let ke=P.length,V=nt(P.map(B=>m[B].scores))??0;P=ht(m.map((B,z)=>({idx:z,scores:B.scores})),this.tieEpsilon).map(B=>B.idx);let ne=nt(P.map(B=>m[B].scores))??0;if(P.length>ke||ne>V+1e-6)C=0,b(`Iteration ${S+1}: Archive improved (size=${P.length}, hv=${ne.toFixed(4)})`);else if(C++,b(`Iteration ${S+1}: Archive unchanged (stagnation=${C}/${this.earlyStoppingTrials})`),C>=this.earlyStoppingTrials){b(`Early stopping: ${C} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let v=ht(m.map((S,E)=>({idx:E,scores:S.scores})),this.tieEpsilon),M=v.length>0?Math.max(...v.map(S=>g(S.scores))):0,F;if(v.length>0){let S=Number.NEGATIVE_INFINITY;for(let E of v){let $=g(E.scores);$>S&&(S=$,F=E.idx)}}let R=nt(v.map(S=>S.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);this.recordParetoMetrics(v.length,m.length,"GEPA",R,w);let I=Date.now()-o,_=typeof F=="number"?new gt({bestScore:M,stats:this.stats,instruction:m[F].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:I,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,k=this.generateOptimizationReport(v,R,M);return{demos:[],stats:this.stats,bestScore:M,paretoFront:v.map(S=>({demos:[],scores:S.scores,configuration:{candidate:S.idx,instruction:m[S.idx].instruction},dominatedSolutions:S.dominated})),paretoFrontSize:v.length,hypervolume:R,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:_,report:k}}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){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,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?Bt(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 s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,s){let a=s??[];if(a.length===0)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});a.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,c=o?.feedbackFn,u=()=>{let m=[];for(let g=0;g<a.length;g++){let h=a[g],f=`# Example ${g+1}
|
|
445
|
+
${e}`}i(n)}},yr=Ni();var Di={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Qo,_p=i=>{if(Qo)return Qo;if(i)return Qo=$p(i),Qo};var Xo=Di,Cc=i=>{Xo={...Xo,...i}},Rc=()=>({...Xo}),$p=i=>({optimizationLatencyHistogram:i.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:i.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:i.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:i.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:i.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:i.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:i.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:i.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:i.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:i.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:i.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:i.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:i.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:i.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:i.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:i.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:i.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:i.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:i.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:i.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:i.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:i.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:i.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:i.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:i.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:i.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:i.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:i.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:i.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:i.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:i.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ut=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Xo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Np=(i,e,t,n,r,o)=>{try{let s=ut({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,s),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,s),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record optimization metric:",s)}},Dp=(i,e,t,n,r,o,s)=>{try{let a=ut({optimizer_type:o,...s});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},Lp=(i,e,t,n)=>{try{let r=ut({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},Gp=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:n,...o});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,s),i.costUsageCounter&&i.costUsageCounter.add(t,s),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,s)}catch(s){console.warn("Failed to record resource usage metric:",s)}},Up=(i,e,t,n)=>{try{let r=ut({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},Bp=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,o),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,o),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},jp=(i,e,t,n,r,o)=>{try{let s=ut({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,s),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,s)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,s),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,s))}catch(s){console.warn("Failed to record checkpoint metric:",s)}},qp=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:n,...o});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,s),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,s),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,s),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,s)}catch(s){console.warn("Failed to record Pareto metric:",s)}},zp=(i,e,t,n,r,o,s)=>{try{let a=ut({optimizer_type:o,...s});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Hp=(i,e,t,n,r)=>{try{let o=ut({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Kp=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,o),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,o),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},gt=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)}},br=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}},qe=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 br({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=_p(X.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?yr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return _t(X.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a,r);let l,c=(g,h,f,x,A,T,y,b={},C)=>{this.getOptimizerLogger(C)?.({name:"RoundProgress",value:{round:g,totalRounds:C?.maxIterations??0,currentScore:h,bestScore:T,configuration:f}}),this.updateOptimizationProgress(g,h,f,x,A,T,y,b,C)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},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,s,a,r),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,s=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(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);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 s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),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:h})=>{let f=await n({prediction:g,example:h}),x=0;for(let[A,T]of Object.entries(f))x+=T*(d[A]||0);return x};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: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 s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[u]||0,f=0;for(let[x,A]of Object.entries(g))x!==u&&A<.3&&(f+=(.3-A)*2);return h-f};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 s of e)o[s]=s===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 s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Ce(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],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[h,f]of Object.entries(g))c[h]||(c[h]=[]),c[h].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=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)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||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,s=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;s+=u*(p-l),l=Math.max(l,p)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.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,s)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown",t)}return s}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,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,s=(t.match(/output:/g)||[]).length;zp(this.metricsInstruments,o,s,0,0,e,r)}Kp(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);Np(this.metricsInstruments,e,t,n,r,s),Up(this.metricsInstruments,e,n,s);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;Gp(this.metricsInstruments,l,a,n,void 0,s)}recordConvergenceMetrics(e,t,n,r,o,s){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(s);Dp(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);Lp(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Bp(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);jp(this.metricsInstruments,e,t,n,r,s)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);qp(this.metricsInstruments,e,t,n,r,s)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Hp(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??X.optimizerLogger??yr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=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: ${s.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 s=this.getOptimizerLogger(r);s&&s(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 wc(i){return be.create(i)}function $e(i,e){let t=typeof i=="string"?be.create(i):i;return new Ce(t,e)}function vc(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function ht(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(vc(i[s].scores,i[n].scores,e)){o=!0;break}vc(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function nt(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-s,0);o+=l*u,s=Math.max(s,c)}return o}function Bt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function Zo(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s: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(i,e){let t=new Set;for(let u of i)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,s=(u,p)=>{for(let d of i){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(s(u,p)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function Tr(i,e,t){let n=Ir(i,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 s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var On=class i extends qe{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;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";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 s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s: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??5)),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 s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(O,E)=>{try{e.setInstruction?.(O);let $=await e.forward(this.studentAI,E,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:$,example:E})||{}}catch{return{}}},p=async(O,E)=>{let $=[];for(let N of E)$.push(await u(O,N));return Zo($)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=O=>{let E=r?.paretoMetricKey,$=r?.paretoScalarize;if(typeof $=="function")return $(O);if(E)return Number.isFinite(O[E])?O[E]:0;let N=Object.values(O);return N.length?N.reduce((L,U)=>L+U,0)/N.length:0},h=[],f=async(O,E)=>{let $=[];for(let N of E){let L=await u(O,N);$.push(g(L))}return $};h.push(await f(d,l));let x=()=>{let O=h[0]?.length??0,E=[];for(let N=0;N<O;N++){let L=Number.NEGATIVE_INFINITY,U=new Set;for(let H=0;H<h.length;H++){let W=h[H][N];W>L+this.tieEpsilon?(L=W,U.clear(),U.add(H)):Math.abs(W-L)<=this.tieEpsilon&&U.add(H)}E.push(U)}let $=h.map(N=>Bt(N));return Tr(E,$)},A=r?.maxMetricCalls;if(!Number.isFinite(A)||A<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let T=Math.floor(A),y=this.getOptimizerLogger(r),b=r?.verbose??this.verbose?O=>console.log(`[GEPA] ${O}`):O=>{};y?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),b(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${T}`);let C=0,P=ht(m.map((O,E)=>({idx:E,scores:O.scores})),this.tieEpsilon).map(O=>O.idx),S;for(let O=0;O<this.numTrials&&!(T!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(T)));O++){let E=h[0]?.length??0,$=[];for(let B=0;B<E;B++){let z=Number.NEGATIVE_INFINITY,Z=new Set;for(let re=0;re<h.length;re++){let G=h[re][B];G>z+this.tieEpsilon?(z=G,Z.clear(),Z.add(re)):Math.abs(G-z)<=this.tieEpsilon&&Z.add(re)}$.push(Z)}let N=h.map(B=>Bt(B));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let B=D=>{let K=[],ee=D;for(;ee!==void 0;)K.push(ee),ee=m[ee]?.parent;return K},z=D=>D.length?D[Math.floor(this.rand()*D.length)]:void 0,Z=Ir($,N),re=new Set;for(let D of Z)for(let K of D)re.add(K);let G=Array.from(re),j;for(let D=0;D<10&&!j&&!(G.length<2);D++){let K=z(G),ee=z(G);if(K===ee)continue;ee<K&&([K,ee]=[ee,K]);let fe=new Set(B(K)),te=new Set(B(ee));if(fe.has(ee)||te.has(K))continue;let se=[...fe].filter(Me=>te.has(Me));if(se.length===0)continue;let ce=se.map(Me=>Math.max(1e-9,N[Me])),ge=this.rand()*ce.reduce((Me,Je)=>Me+Je,0),ve=se[se.length-1];for(let Me=0;Me<se.length;Me++){if(ge<ce[Me]){ve=se[Me];break}ge-=ce[Me]}j={i:K,j:ee,a:ve}}if(this.lastIterFoundNewProgram=!1,j){let{i:D,j:K,a:ee}=j,fe=N[ee],te=N[D],se=N[K],ce=m[ee].instruction,ge=m[D].instruction,ve=m[K].instruction,Me=ge===ce&&ve!==ge||ve===ce&&ge!==ve,Je=fe<=Math.min(te,se)&&Me,Ne="",He="i",he=!1;if(Je){let ft=`${D}|${K}|${ee}`;if(this.mergeAttemptKeys.has(ft))Je=!1;else{ge===ce&&ve!==ge?(Ne=ve,He="j"):ve===ce&&ge!==ve?(Ne=ge,He="i"):ge!==ce&&ve!==ce&&ge!==ve?te>se||te===se&&this.rand()<.5?(Ne=ge,He="i"):(Ne=ve,He="j"):(Ne=ge,He="i");let Tt=`${Math.min(D,K)}|${Math.max(D,K)}|${He}`;if(this.mergeCompositionKeys.has(Tt))Je=!1;else{this.mergeAttemptKeys.add(ft),this.mergeCompositionKeys.add(Tt);let rt=h[D],Ct=h[K],Rt=Array.from({length:rt.length},(pe,De)=>De),xt=Rt.filter(pe=>(rt[pe]??0)>(Ct[pe]??0)),wt=Rt.filter(pe=>(Ct[pe]??0)>(rt[pe]??0)),Ft=Rt.filter(pe=>!(xt.includes(pe)||wt.includes(pe))),Y=5,Ie=Math.ceil(Y/3),pt=(pe,De)=>{if(De<=0||pe.length===0)return[];if(pe.length<=De)return[...pe];let Ln=[],Mr=new Set;for(;Ln.length<De;){let ot=Math.floor(this.rand()*pe.length);Mr.has(ot)||(Mr.add(ot),Ln.push(pe[ot]))}return Ln},Ke=[];Ke.push(...pt(xt,Math.min(Ie,xt.length))),Ke.push(...pt(wt,Math.min(Ie,wt.length)));let Ve=Y-Ke.length;Ke.push(...pt(Ft,Math.max(0,Ve)));let kr=Y-Ke.length;if(kr>0){let pe=Rt.filter(De=>!Ke.includes(De));Ke.push(...pt(pe,Math.min(kr,pe.length)))}let gs=Ke.slice(0,Math.min(Y,Rt.length)),Hc=gs.map(pe=>l[pe]);he=!0;let Kc=(await f(Ne,Hc)).reduce((pe,De)=>pe+De,0),Vc=gs.reduce((pe,De)=>pe+(rt[De]??0),0),Wc=gs.reduce((pe,De)=>pe+(Ct[De]??0),0);if(Kc>=Math.max(Vc,Wc)+this.tieEpsilon){b(`Iteration ${O+1}: Merge accepted (programs ${D} + ${K} via ancestor ${ee})`);let pe=await p(Ne,l);m.push({instruction:Ne,parent:ee,scores:pe}),h.push(await f(Ne,l));let De=P.length,Ln=nt(P.map(ot=>m[ot].scores))??0;P=ht(m.map((ot,Jc)=>({idx:Jc,scores:ot.scores})),this.tieEpsilon).map(ot=>ot.idx);let Mr=nt(P.map(ot=>m[ot].scores))??0;(P.length>De||Mr>Ln+1e-6)&&(C=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(he)continue}}let L=Tr($,N,()=>this.rand()),U=this.minibatch?this.nextMinibatchIndices(c.length,O).map(B=>c[B]):c;if(r?.skipPerfectScore??!0){let B=Number(r?.perfectScore??1),z=await f(m[L].instruction,U);if(z.length>0&&z.every(Z=>Z>=B))continue}let H=!1,W=m[L].instruction,ue="reflective_mutation",ae,me;if(H){let B=(L+1)%m.length;W=await this.mergeInstructions(m[L].instruction,m[B].instruction,r),ue="merge",this.mergesUsed+=1}else{let B=r?.gepaAdapter;if(B){try{let z={instruction:m[L].instruction},Z=await B.evaluate(U,z,!0);ae=Array.isArray(Z?.scores)?Z.scores.reduce((D,K)=>D+(Number(K)||0),0):void 0;let re=B.make_reflective_dataset(z,Z,["instruction"]),G=await B.propose_new_texts?.(z,re,["instruction"]),j=G?.instruction??(G?Object.values(G)[0]:void 0);typeof j=="string"&&j.length>0?W=j:W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:D,example:K})=>{let ee=await n({prediction:D,example:K}),fe=Object.values(ee||{});return fe.length?fe.reduce((te,se)=>te+se,0)/fe.length:0},r)}catch{W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)}if(ae!==void 0)try{let z=await B.evaluate(U,{instruction:W},!1);me=Array.isArray(z?.scores)?z.scores.reduce((Z,re)=>Z+(Number(re)||0),0):void 0}catch{}}else W=await this.reflectInstruction(m[L].instruction,e,U,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)}let le=await f(m[L].instruction,U),oe=await f(W,U),Re=le.reduce((B,z)=>B+z,0),ye=oe.reduce((B,z)=>B+z,0);if(this.currentRound=O+1,await this.updateOptimizationProgress(this.currentRound,ye,{instructionLen:W.length,parent:L,totalRounds:this.numTrials},"GEPA",{strategy:ue,paretoSetSize:l.length},ye,{instructionLen:m[L].instruction.length,idx:L},{...r??{},maxIterations:this.numTrials}),!(ye>Re+this.tieEpsilon&&(ae===void 0||me===void 0||me>ae+this.tieEpsilon))){if(b(`Iteration ${O+1}: Rejected (child=${ye.toFixed(3)} <= parent=${Re.toFixed(3)})`),++C>=this.earlyStoppingTrials){b(`Early stopping: ${C} iterations without improvement`);break}continue}b(`Iteration ${O+1}: Accepted (child=${ye.toFixed(3)} > parent=${Re.toFixed(3)})`);let xe=await p(W,l);m.push({instruction:W,parent:L,scores:xe}),h.push(await f(W,l));let ke=P.length,V=nt(P.map(B=>m[B].scores))??0;P=ht(m.map((B,z)=>({idx:z,scores:B.scores})),this.tieEpsilon).map(B=>B.idx);let ne=nt(P.map(B=>m[B].scores))??0;if(P.length>ke||ne>V+1e-6)C=0,b(`Iteration ${O+1}: Archive improved (size=${P.length}, hv=${ne.toFixed(4)})`);else if(C++,b(`Iteration ${O+1}: Archive unchanged (stagnation=${C}/${this.earlyStoppingTrials})`),C>=this.earlyStoppingTrials){b(`Early stopping: ${C} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let v=ht(m.map((O,E)=>({idx:E,scores:O.scores})),this.tieEpsilon),k=v.length>0?Math.max(...v.map(O=>g(O.scores))):0,F;if(v.length>0){let O=Number.NEGATIVE_INFINITY;for(let E of v){let $=g(E.scores);$>O&&(O=$,F=E.idx)}}let R=nt(v.map(O=>O.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);this.recordParetoMetrics(v.length,m.length,"GEPA",R,w);let I=Date.now()-o,_=typeof F=="number"?new gt({bestScore:k,stats:this.stats,instruction:m[F].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:I,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,M=this.generateOptimizationReport(v,R,k);return{demos:[],stats:this.stats,bestScore:k,paretoFront:v.map(O=>({demos:[],scores:O.scores,configuration:{candidate:O.idx,instruction:m[O.idx].instruction},dominatedSolutions:O.dominated})),paretoFrontSize:v.length,hypervolume:R,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:_,report:M}}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){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,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?Bt(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 s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,s){let a=s??[];if(a.length===0)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});a.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,c=o?.feedbackFn,u=()=>{let m=[];for(let g=0;g<a.length;g++){let h=a[g],f=`# Example ${g+1}
|
|
446
446
|
`;if(f+=`## Inputs
|
|
447
447
|
`,typeof h.input=="object"&&h.input!==null)for(let[A,T]of Object.entries(h.input))f+=`### ${A}
|
|
448
448
|
${String(T).trim()}
|
|
@@ -494,7 +494,7 @@ ${n.map(s=>`- ${s}`).join(`
|
|
|
494
494
|
`)}
|
|
495
495
|
|
|
496
496
|
Output ONLY the JSON array, no explanation.
|
|
497
|
-
`.trim(),o=new Ce("count:number -> examples:json");o.setInstruction(r);try{let s=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(s.examples)?s.examples.slice(0,e):[]}catch(s){return console.warn("AxSynth: Edge case generation failed:",s),[]}}async labelInput(e){return await new Ce(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var es=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Sn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,s=[...n.examples??[]];if(n.useTraces!==!1){let C=(await this.getTraces()).filter(P=>P.input&&P.output).map(P=>({...P.input,...P.output}));s=[...s,...C]}if(n.generateExamples||s.length===0){let b=n.synthCount??20,C={teacher:r,...n.synthOptions},v=(await new kn(this.gen.getSignature(),C).generate(b)).examples.map(
|
|
497
|
+
`.trim(),o=new Ce("count:number -> examples:json");o.setInstruction(r);try{let s=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(s.examples)?s.examples.slice(0,e):[]}catch(s){return console.warn("AxSynth: Edge case generation failed:",s),[]}}async labelInput(e){return await new Ce(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var es=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Sn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,s=[...n.examples??[]];if(n.useTraces!==!1){let C=(await this.getTraces()).filter(P=>P.input&&P.output).map(P=>({...P.input,...P.output}));s=[...s,...C]}if(n.generateExamples||s.length===0){let b=n.synthCount??20,C={teacher:r,...n.synthOptions},v=(await new kn(this.gen.getSignature(),C).generate(b)).examples.map(k=>({...k.input,...k.expected}));s=[...s,...v]}if(s.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...s].sort(()=>Math.random()-.5),c=Math.floor(l.length*(1-a)),u=l.slice(0,c),p=l.slice(c),d=n.metric;if(!d){let b={ai:r,criteria:n.criteria,...n.judgeOptions};d=new vn(this.gen.getSignature(),b).toMetricFn()}let m=new On({studentAI:r,numTrials:o,minibatch:!0,minibatchSize:10}),g=o*Math.max(u.length,10),h=await m.compile(this.gen,u,d,{validationExamples:p,maxMetricCalls:g});if(!h.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");h.optimizedProgram.instruction&&this.gen.setInstruction(h.optimizedProgram.instruction),this.currentScore=h.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,x=f,T=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,y={type:"checkpoint",name:this.options.name,version:T,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:o,trainingExamples:u.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,y),{score:f,improvement:x,checkpointVersion:T,stats:{trainingExamples:u.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var ts=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 s={};return t.forEach(a=>{let l=a.split("."),c=o.row;for(let p of l)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);s[u]=c}),s}).filter(o=>Object.keys(o).length!==0)}};var Oc=Gn(tu("crypto"),1);function Li(i){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:i}}function jt(i){return JSON.parse(JSON.stringify(i))}function Wp(i){return Math.ceil(i.length/4)}function Gi(i,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:s=!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(!i.sections[p.section]){if(!s)continue;i.sections[p.section]=[]}let d=i.sections[p.section];switch(p.type){case"ADD":{if(d.length>=o){if(!a)continue;let h=Yp(d,u);if(!h)continue;n.push(h.id),r.push({type:"REMOVE",section:p.section,bulletId:h.id,metadata:{...h.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??Jp(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 ji(i),i.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function Ui(i,e,t){for(let n of Object.values(i.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(),ji(i);return}}}function Cr(i){let e=i.description?`## Context Playbook
|
|
498
498
|
${i.description.trim()}
|
|
499
499
|
`:`## Context Playbook
|
|
500
500
|
`,t=Object.entries(i.sections).map(([n,r])=>{let o=r.map(s=>`- [${s.id}] ${s.content}`).join(`
|
|
@@ -505,9 +505,9 @@ _(empty)_`}).join(`
|
|
|
505
505
|
`);return`${e}
|
|
506
506
|
${t}`.trim()}function Jp(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Oc.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Yp(i,e){let t=-1,n;for(let o=0;o<i.length;o+=1){let s=i[o];if(e.has(s.id))continue;let a=s.helpfulCount??0,l=s.harmfulCount??0,c=a-l*2,u=Date.parse(s.updatedAt??s.createdAt),p=[c,a,Number.isFinite(u)?u:Number.POSITIVE_INFINITY];if(!n){t=o,n=p;continue}let d=i[t],m=d.helpfulCount??0,g=d.harmfulCount??0,h=m-g*2,f=Date.parse(d.updatedAt??d.createdAt),x=[h,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(p[0]<x[0]||p[0]===x[0]&&p[1]<x[1]||p[0]===x[0]&&p[1]===x[1]&&p[2]<x[2])&&(t=o,n=p)}if(t===-1)return;let[r]=i.splice(t,1);return r}function Bi(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,o=[];for(let s of n){let a=s.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=s.helpfulCount,l.harmfulCount+=s.harmfulCount,l.updatedAt=s.updatedAt):(r.set(a,s),o.push(s))}i.sections[t]=o}ji(i)}function ji(i){let e=0,t=0,n=0,r=0;for(let o of Object.values(i.sections))for(let s of o)e+=1,t+=s.helpfulCount,n+=s.harmfulCount,r+=Wp(s.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Qp={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},Rr=class extends gt{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=jt(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(),"",Cr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
|
|
507
507
|
|
|
508
|
-
`);e.setDescription(r)}},ns=class extends qe{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Qp,...t},this.playbook=t?.initialPlaybook!==void 0?jt(t.initialPlaybook):Li()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?jt(this.aceConfig.initialPlaybook):Li(),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=jt(o.initialPlaybook)));let s=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let x=0;x<p;x++)for(let A=0;A<t.length;A++){let T=t[A],y=this.composeInstruction(a??l,this.playbook);e.setDescription?.(y);let b=await e.forward(this.studentAI,T);this.stats.totalCalls+=1;let C=await n({prediction:b,example:T});typeof C=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,C),c=Math.max(c,C));let P=b?.severity,
|
|
508
|
+
`);e.setDescription(r)}},ns=class extends qe{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Qp,...t},this.playbook=t?.initialPlaybook!==void 0?jt(t.initialPlaybook):Li()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?jt(this.aceConfig.initialPlaybook):Li(),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=jt(o.initialPlaybook)));let s=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let x=0;x<p;x++)for(let A=0;A<t.length;A++){let T=t[A],y=this.composeInstruction(a??l,this.playbook);e.setDescription?.(y);let b=await e.forward(this.studentAI,T);this.stats.totalCalls+=1;let C=await n({prediction:b,example:T});typeof C=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,C),c=Math.max(c,C));let P=b?.severity,S=T?.severity,v=this.createGeneratorOutput(b,T),k=S&&P&&S!==P,F=await this.runReflectionRounds({example:T,generatorOutput:v,feedback:S&&P&&S!==P?`Expected severity "${S}" but model predicted "${P}".`:void 0}),R=await this.runCurator({program:e,example:T,reflection:F,playbook:this.playbook}),w=this.normalizeCuratorOperations(R?.operations);w.length===0&&k&&(w=this.inferOperationsFromReflection(F)),w=this.resolveCuratorOperationTargets(w,this.playbook,F,v);let I=R||w.length>0?{...R??{},operations:w}:void 0,_=[];if(w.length>0){let N=this.collectProtectedBulletIds(w),L=Gi(this.playbook,w,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:N});_=L.updatedBulletIds,L.autoRemoved.length>0&&(w.push(...L.autoRemoved),I&&(I.operations=w))}if(F?.bulletTags)for(let N of F.bulletTags)Ui(this.playbook,N.id,N.tag);w.length>0&&_.length>0&&Bi(this.playbook,this.aceConfig.similarityThreshold);let M={example:T,prediction:b,score:typeof C=="number"?C:0,generatorOutput:v,reflection:F,curator:I,timestamp:new Date().toISOString()};this.generatorHistory.push(M),_.length>0&&I?.operations?.length&&this.deltaHistory.push({epoch:x,exampleIndex:A,operations:I.operations}),u+=1,this.currentRound=u;let O=typeof C=="number"&&Number.isFinite(C)?C:0,E=Number.isFinite(c)?c:O,$={...r??{},maxIterations:d};await this.updateOptimizationProgress(u,O,{epoch:x,exampleIndex:A,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},E,{playbookBullets:this.playbook.stats.bulletCount},void 0,$),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,O)}}finally{e.setDescription?.(l)}let m=Date.now()-s;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let g={playbook:jt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},h=new Rr({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:p},optimizedProgram:h,playbook:jt(this.playbook),artifact:g}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");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)}),s=await this.runCurator({program:this.program,example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(s?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let c=s||a.length>0?{...s??{},operations:a}:void 0;if(o?.bulletTags)for(let p of o.bulletTags)Ui(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Gi(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Bi(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(),"",Cr(t)].filter(r=>r.trim().length>0).join(`
|
|
509
509
|
|
|
510
|
-
`)}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=[],s=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(s.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,s);let d=g=>{for(;g.length>0;){let h=g.shift();if(!s.has(h))return h}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,s)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,s.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",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="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,h=[a,c,p,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let x=r.metadata;x&&typeof x=="object"&&(f.metadata={...x}),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,s)=>{if(!s)return;let a=s.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 s=0;s<r;s++){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(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(s,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:Cr(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({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),s=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await o.forward(s,{playbook:JSON.stringify({markdown:Cr(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=de().input("question",de.string("Original task input serialized as JSON")).input("generator_answer",de.string("Generator output serialized as JSON")).input("generator_reasoning",de.string("Generator reasoning trace").optional()).input("playbook",de.string("Current context playbook rendered as markdown")).input("expected_answer",de.string("Expected output when ground truth is available").optional()).input("feedback",de.string("External feedback or reward signal").optional()).input("previous_reflection",de.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",de.string("Step-by-step analysis of generator performance")).output("errorIdentification",de.string("Specific mistakes detected")).output("rootCauseAnalysis",de.string("Underlying cause of the error")).output("correctApproach",de.string("What the generator should do differently")).output("keyInsight",de.string("Reusable insight to remember")).output("bulletTags",de.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=$e(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=de().input("playbook",de.string("Current playbook serialized as JSON")).input("reflection",de.string("Latest reflection output serialized as JSON")).input("question_context",de.string("Original task input serialized as JSON")).input("token_budget",de.number("Approximate token budget for curator response").optional()).output("reasoning",de.string("Justification for the proposed updates")).output("operations",de.json("List of operations with type/section/content fields")).build();this.curatorProgram=$e(e)}return this.curatorProgram}};var Mn=class extends qe{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 s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Zp([...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(x=>x!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let x={...l,maxRetries:1};f=await e.forward(h,m,x),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(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),f={}}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 s=Xp(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:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Xp(i){let e=new Map;for(let n of i)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 Zp=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};var rs=class extends qe{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(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.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(w,I)=>{try{s.setAllNodeInstructions?.(w);let _=await s.forward(this.studentAI,I,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:_,example:I})||{}}catch{return{}}},g=async(w,I)=>{let _=[];for(let k of I)_.push(await m(w,k));return Zo(_)},h={};for(let w of a)h[w.name]=await this.getBaseInstruction(w.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,u)}],x=w=>{let I=r?.paretoMetricKey,_=r?.paretoScalarize;if(typeof _=="function")return _(w);if(I)return Number.isFinite(w[I])?w[I]:0;let k=Object.values(w);return k.length?k.reduce((S,E)=>S+E,0)/k.length:0},A=[],T=async(w,I)=>{let _=[];for(let k of I){let S=await m(w,k);_.push(x(S))}return _};A.push(await T(h,u));let y=ht(f.map((w,I)=>({idx:I,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),b=0,C=new Set,P=r?.maxMetricCalls;if(!Number.isFinite(P)||P<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let O=Math.floor(P);for(let w=0;w<this.numTrials&&!(O!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(O)));w++){let I=A[0]?.length??0,_=[];for(let V=0;V<I;V++){let ne=Number.NEGATIVE_INFINITY,B=new Set;for(let z=0;z<A.length;z++){let Z=A[z][V];Z>ne+this.tieEpsilon?(ne=Z,B.clear(),B.add(z)):Math.abs(Z-ne)<=this.tieEpsilon&&B.add(z)}_.push(B)}let k=A.map(V=>Bt(V));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let V=Ir(_,k),ne=new Set;for(let G of V)for(let j of G)ne.add(j);let B=Array.from(ne),z=G=>{let j=[],D=G;for(;D!==void 0;)j.push(D),D=f[D]?.parent;return j},Z=G=>G.length?G[Math.floor(this.rand()*G.length)]:void 0,re;for(let G=0;G<10&&!re&&!(B.length<2);G++){let j=Z(B),D=Z(B);if(j===D)continue;D<j&&([j,D]=[D,j]);let K=new Set(z(j)),ee=new Set(z(D));if(K.has(D)||ee.has(j))continue;let fe=[...K].filter(he=>ee.has(he));if(fe.length===0)continue;let te=[];for(let he of fe){let ft=f[he].cfg,Tt=f[j].cfg,rt=f[D].cfg,Ct=!1,Rt=new Set([...Object.keys(ft),...Object.keys(Tt),...Object.keys(rt)]);for(let xt of Rt){let wt=ft[xt],Ft=Tt[xt],Y=rt[xt];if(Ft===wt&&Y!==Ft||Y===wt&&Ft!==Y){Ct=!0;break}}Ct&&te.push(he)}if(te.length===0)continue;let se=te.map(he=>Math.max(1e-9,k[he])),ce=this.rand()*se.reduce((he,ft)=>he+ft,0),ge=te[te.length-1];for(let he=0;he<te.length;he++){if(ce<se[he]){ge=te[he];break}ce-=se[he]}let ve=k[ge],Me=k[j],Je=k[D];if(ve>Math.min(Me,Je))continue;let Ne=`${j}|${D}|${ge}`;if(this.mergeAttemptKeys.has(Ne))continue;this.mergeAttemptKeys.add(Ne);let He=`${j}|${D}|${ge}`;C.has(He)||(re={i:j,j:D,a:ge})}if(this.lastIterFoundNewProgram=!1,re){let{i:G,j,a:D}=re,{cfg:K,descSig:ee}=this.systemAwareMergeWithSig(f,G,j,(Y,Ie)=>k[Y]>=k[Ie]?Y:Ie),fe=`${Math.min(G,j)}|${Math.max(G,j)}|${ee}`;if(this.mergeCompositionKeys.has(fe))continue;this.mergeCompositionKeys.add(fe);let te=A[G],se=A[j],ce=Array.from({length:te.length},(Y,Ie)=>Ie),ge=ce.filter(Y=>(te[Y]??0)>(se[Y]??0)),ve=ce.filter(Y=>(se[Y]??0)>(te[Y]??0)),Me=ce.filter(Y=>!(ge.includes(Y)||ve.includes(Y))),Je=5,Ne=Math.ceil(Je/3),He=(Y,Ie)=>{if(Ie<=0||Y.length===0)return[];if(Y.length<=Ie)return[...Y];let pt=[],Ke=new Set;for(;pt.length<Ie;){let Ve=Math.floor(this.rand()*Y.length);Ke.has(Ve)||(Ke.add(Ve),pt.push(Y[Ve]))}return pt},he=[];he.push(...He(ge,Math.min(Ne,ge.length))),he.push(...He(ve,Math.min(Ne,ve.length)));let ft=Je-he.length;he.push(...He(Me,Math.max(0,ft)));let Tt=Je-he.length;if(Tt>0){let Y=ce.filter(Ie=>!he.includes(Ie));he.push(...He(Y,Math.min(Tt,Y.length)))}let rt=he.slice(0,Math.min(Je,ce.length)),Ct=rt.map(Y=>u[Y]),xt=(await T(K,Ct)).reduce((Y,Ie)=>Y+Ie,0),wt=rt.reduce((Y,Ie)=>Y+(te[Ie]??0),0),Ft=rt.reduce((Y,Ie)=>Y+(se[Ie]??0),0);if(xt>=Math.max(wt,Ft)+this.tieEpsilon){let Y=await g(K,u);f.push({cfg:K,parent:D,scores:Y}),A.push(await T(K,u));let Ie=y.length,pt=nt(y.map(Ve=>f[Ve].scores))??0;y=ht(f.map((Ve,kr)=>({idx:kr,scores:Ve.scores})),this.tieEpsilon).map(Ve=>Ve.idx);let Ke=nt(y.map(Ve=>f[Ve].scores))??0;(y.length>Ie||Ke>pt+1e-6)&&(b=0),this.mergesDue-=1,this.totalMergesTested+=1,C.add(`${Math.min(G,j)}|${Math.max(G,j)}|${D}`)}continue}}let S=Tr(_,k,()=>this.rand());this.lastIterFoundNewProgram=!1;let E=this.minibatch?this.nextMinibatchIndices(p.length,w).map(V=>p[V]):p;if(r?.skipPerfectScore??!0){let V=Number(r?.perfectScore??1),ne=await T(f[S].cfg,E);if(ne.length>0&&ne.every(B=>B>=V))continue}let $=!1,N={...f[S].cfg},L="reflective_mutation",U=w%a.length,H=a[U],W,ue;if($&&this.mergesUsed<this.mergeMax){let V=(S+1)%f.length,ne=G=>{let j=[],D=G;for(;D!==void 0;)j.push(D),D=f[D]?.parent;return j},B=ne(S),z=ne(V),Z=B.find(G=>z.includes(G)),re=!0;if(Z||(re=!1),(z.includes(S)||B.includes(V))&&(re=!1),re){let G=f[Z].cfg,j=f[S].cfg,D=f[V].cfg,K=!1,ee=new Set([...Object.keys(G),...Object.keys(j),...Object.keys(D)]);for(let fe of ee){let te=G[fe],se=j[fe],ce=D[fe];if(se===te&&ce!==se||ce===te&&se!==ce){K=!0;break}}K||(re=!1)}if(re){let G=Math.min(S,V),j=Math.max(S,V),D=`${G}|${j}|${Z}`;if(!C.has(D)){let K=x(f[Z].scores),ee=x(f[S].scores),fe=x(f[V].scores);K<=Math.min(ee,fe)&&(N=this.systemAwareMerge(f,S,V,(te,se)=>{let ce=x(f[te].scores),ge=x(f[se].scores);return ce>=ge?te:se}),L="system_merge",this.mergesUsed+=1,C.add(D))}}else{let G=f[S].cfg[H.name],j=r?.gepaAdapter,D;if(j)try{let K=await j.evaluate(E,{...f[S].cfg},!0);W=Array.isArray(K?.scores)?K.scores.reduce((se,ce)=>se+(Number(ce)||0),0):void 0;let ee=j.make_reflective_dataset({...f[S].cfg},K,[H.name]),te=(await j.propose_new_texts?.({...f[S].cfg},ee,[H.name]))?.[H.name];typeof te=="string"&&te.length>0&&(D=te)}catch{}if(D||(D=await this.reflectModuleInstruction(H.name,G,s,a,{...f[S].cfg},E,async({prediction:K,example:ee})=>{let fe=await n({prediction:K,example:ee}),te=Object.values(fe||{});return te.length?te.reduce((se,ce)=>se+ce,0)/te.length:0},r)),N[H.name]=D,j&&W!==void 0)try{let K=await j.evaluate(E,N,!1);ue=Array.isArray(K?.scores)?K.scores.reduce((ee,fe)=>ee+(Number(fe)||0),0):void 0}catch{}}}else{let V=f[S].cfg[H.name],ne=r?.gepaAdapter,B;if(ne)try{let z=await ne.evaluate(E,{...f[S].cfg},!0);W=Array.isArray(z?.scores)?z.scores.reduce((j,D)=>j+(Number(D)||0),0):void 0;let Z=ne.make_reflective_dataset({...f[S].cfg},z,[H.name]),G=(await ne.propose_new_texts?.({...f[S].cfg},Z,[H.name]))?.[H.name];typeof G=="string"&&G.length>0&&(B=G)}catch{}if(B||(B=await this.reflectModuleInstruction(H.name,V,s,a,{...f[S].cfg},E,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)),N[H.name]=B,ne&&W!==void 0)try{let z=await ne.evaluate(E,N,!1);ue=Array.isArray(z?.scores)?z.scores.reduce((Z,re)=>Z+(Number(re)||0),0):void 0}catch{}}let ae=await T(f[S].cfg,E),me=await T(N,E),le=ae.reduce((V,ne)=>V+ne,0),oe=me.reduce((V,ne)=>V+ne,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,oe,{modules:a.length,mutatedModule:H.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:L,paretoSetSize:u.length},oe,{idx:S},{...r??{},maxIterations:this.numTrials}),!(oe>le+this.tieEpsilon&&(W===void 0||ue===void 0||ue>W+this.tieEpsilon))){if(++b>=this.earlyStoppingTrials)break;continue}let ye=await g(N,u);f.push({cfg:N,parent:S,scores:ye}),A.push(await T(N,u));let ze=y.length,xe=nt(y.map(V=>f[V].scores))??0;y=ht(f.map((V,ne)=>({idx:ne,scores:V.scores})),this.tieEpsilon).map(V=>V.idx);let ke=nt(y.map(V=>f[V].scores))??0;if(y.length>ze||ke>xe+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 v=ht(f.map((w,I)=>({idx:I,scores:w.scores})),this.tieEpsilon),M=v.length>0?Math.max(...v.map(w=>x(w.scores))):0,F=nt(v.map(w=>w.scores));this.stats.convergenceInfo.converged=!0;let R=this.getMergedCustomLabels(r);return this.recordParetoMetrics(v.length,f.length,"GEPA-Flow",F,R),{demos:[],stats:this.stats,bestScore:M,paretoFront:v.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:v.length,hypervolume:F,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,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?Bt(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 s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],u=[];for(let x of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let T=await a({prediction:A,example:x});u.push({input:x,prediction:A,score:typeof T=="number"?T:0})}catch{u.push({input:x,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=$e('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 x of u){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let h="";try{h=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=$e('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 A=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:h,minibatch:u}))?.newInstruction?.trim();if(A&&A.length>16)return A}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,s=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=s[l%s.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 s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=f=>{let x=[],A=f;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of h){let x=u[f],A=p[f],T=d[f];if(A===x&&T!==A)m[f]=T,g.push("j");else if(T===x&&A!==T)m[f]=A,g.push("i");else if(A!==T&&A!==x&&T!==x){let y=r(t,n);m[f]=y===t?A:T,g.push(y===t?"i":"j")}else m[f]=A??T??x,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=[],x=h;for(;x!==void 0;)f.push(x),x=e[x]?.parent;return f},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??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 h of g){let f=u[h],x=p[h],A=d[h];if(x===f&&A!==x)m[h]=A;else if(A===f&&x!==A)m[h]=x;else if(x!==A&&x!==f&&A!==f){let T=r(t,n);m[h]=T===t?x:A}else m[h]=x??A??f}return m}};var os=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 s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),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 ss=class extends qe{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 os(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,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=`
|
|
510
|
+
`)}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=[],s=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(s.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,s);let d=g=>{for(;g.length>0;){let h=g.shift();if(!s.has(h))return h}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,s)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,s.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",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="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,h=[a,c,p,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let x=r.metadata;x&&typeof x=="object"&&(f.metadata={...x}),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,s)=>{if(!s)return;let a=s.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 s=0;s<r;s++){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(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(s,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:Cr(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({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),s=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await o.forward(s,{playbook:JSON.stringify({markdown:Cr(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=de().input("question",de.string("Original task input serialized as JSON")).input("generator_answer",de.string("Generator output serialized as JSON")).input("generator_reasoning",de.string("Generator reasoning trace").optional()).input("playbook",de.string("Current context playbook rendered as markdown")).input("expected_answer",de.string("Expected output when ground truth is available").optional()).input("feedback",de.string("External feedback or reward signal").optional()).input("previous_reflection",de.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",de.string("Step-by-step analysis of generator performance")).output("errorIdentification",de.string("Specific mistakes detected")).output("rootCauseAnalysis",de.string("Underlying cause of the error")).output("correctApproach",de.string("What the generator should do differently")).output("keyInsight",de.string("Reusable insight to remember")).output("bulletTags",de.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=$e(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=de().input("playbook",de.string("Current playbook serialized as JSON")).input("reflection",de.string("Latest reflection output serialized as JSON")).input("question_context",de.string("Original task input serialized as JSON")).input("token_budget",de.number("Approximate token budget for curator response").optional()).output("reasoning",de.string("Justification for the proposed updates")).output("operations",de.json("List of operations with type/section/content fields")).build();this.curatorProgram=$e(e)}return this.curatorProgram}};var Mn=class extends qe{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 s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Zp([...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(x=>x!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let x={...l,maxRetries:1};f=await e.forward(h,m,x),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(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),f={}}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 s=Xp(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:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Xp(i){let e=new Map;for(let n of i)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 Zp=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};var rs=class extends qe{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(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.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(w,I)=>{try{s.setAllNodeInstructions?.(w);let _=await s.forward(this.studentAI,I,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:_,example:I})||{}}catch{return{}}},g=async(w,I)=>{let _=[];for(let M of I)_.push(await m(w,M));return Zo(_)},h={};for(let w of a)h[w.name]=await this.getBaseInstruction(w.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,u)}],x=w=>{let I=r?.paretoMetricKey,_=r?.paretoScalarize;if(typeof _=="function")return _(w);if(I)return Number.isFinite(w[I])?w[I]:0;let M=Object.values(w);return M.length?M.reduce((O,E)=>O+E,0)/M.length:0},A=[],T=async(w,I)=>{let _=[];for(let M of I){let O=await m(w,M);_.push(x(O))}return _};A.push(await T(h,u));let y=ht(f.map((w,I)=>({idx:I,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),b=0,C=new Set,P=r?.maxMetricCalls;if(!Number.isFinite(P)||P<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let S=Math.floor(P);for(let w=0;w<this.numTrials&&!(S!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(S)));w++){let I=A[0]?.length??0,_=[];for(let V=0;V<I;V++){let ne=Number.NEGATIVE_INFINITY,B=new Set;for(let z=0;z<A.length;z++){let Z=A[z][V];Z>ne+this.tieEpsilon?(ne=Z,B.clear(),B.add(z)):Math.abs(Z-ne)<=this.tieEpsilon&&B.add(z)}_.push(B)}let M=A.map(V=>Bt(V));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let V=Ir(_,M),ne=new Set;for(let G of V)for(let j of G)ne.add(j);let B=Array.from(ne),z=G=>{let j=[],D=G;for(;D!==void 0;)j.push(D),D=f[D]?.parent;return j},Z=G=>G.length?G[Math.floor(this.rand()*G.length)]:void 0,re;for(let G=0;G<10&&!re&&!(B.length<2);G++){let j=Z(B),D=Z(B);if(j===D)continue;D<j&&([j,D]=[D,j]);let K=new Set(z(j)),ee=new Set(z(D));if(K.has(D)||ee.has(j))continue;let fe=[...K].filter(he=>ee.has(he));if(fe.length===0)continue;let te=[];for(let he of fe){let ft=f[he].cfg,Tt=f[j].cfg,rt=f[D].cfg,Ct=!1,Rt=new Set([...Object.keys(ft),...Object.keys(Tt),...Object.keys(rt)]);for(let xt of Rt){let wt=ft[xt],Ft=Tt[xt],Y=rt[xt];if(Ft===wt&&Y!==Ft||Y===wt&&Ft!==Y){Ct=!0;break}}Ct&&te.push(he)}if(te.length===0)continue;let se=te.map(he=>Math.max(1e-9,M[he])),ce=this.rand()*se.reduce((he,ft)=>he+ft,0),ge=te[te.length-1];for(let he=0;he<te.length;he++){if(ce<se[he]){ge=te[he];break}ce-=se[he]}let ve=M[ge],Me=M[j],Je=M[D];if(ve>Math.min(Me,Je))continue;let Ne=`${j}|${D}|${ge}`;if(this.mergeAttemptKeys.has(Ne))continue;this.mergeAttemptKeys.add(Ne);let He=`${j}|${D}|${ge}`;C.has(He)||(re={i:j,j:D,a:ge})}if(this.lastIterFoundNewProgram=!1,re){let{i:G,j,a:D}=re,{cfg:K,descSig:ee}=this.systemAwareMergeWithSig(f,G,j,(Y,Ie)=>M[Y]>=M[Ie]?Y:Ie),fe=`${Math.min(G,j)}|${Math.max(G,j)}|${ee}`;if(this.mergeCompositionKeys.has(fe))continue;this.mergeCompositionKeys.add(fe);let te=A[G],se=A[j],ce=Array.from({length:te.length},(Y,Ie)=>Ie),ge=ce.filter(Y=>(te[Y]??0)>(se[Y]??0)),ve=ce.filter(Y=>(se[Y]??0)>(te[Y]??0)),Me=ce.filter(Y=>!(ge.includes(Y)||ve.includes(Y))),Je=5,Ne=Math.ceil(Je/3),He=(Y,Ie)=>{if(Ie<=0||Y.length===0)return[];if(Y.length<=Ie)return[...Y];let pt=[],Ke=new Set;for(;pt.length<Ie;){let Ve=Math.floor(this.rand()*Y.length);Ke.has(Ve)||(Ke.add(Ve),pt.push(Y[Ve]))}return pt},he=[];he.push(...He(ge,Math.min(Ne,ge.length))),he.push(...He(ve,Math.min(Ne,ve.length)));let ft=Je-he.length;he.push(...He(Me,Math.max(0,ft)));let Tt=Je-he.length;if(Tt>0){let Y=ce.filter(Ie=>!he.includes(Ie));he.push(...He(Y,Math.min(Tt,Y.length)))}let rt=he.slice(0,Math.min(Je,ce.length)),Ct=rt.map(Y=>u[Y]),xt=(await T(K,Ct)).reduce((Y,Ie)=>Y+Ie,0),wt=rt.reduce((Y,Ie)=>Y+(te[Ie]??0),0),Ft=rt.reduce((Y,Ie)=>Y+(se[Ie]??0),0);if(xt>=Math.max(wt,Ft)+this.tieEpsilon){let Y=await g(K,u);f.push({cfg:K,parent:D,scores:Y}),A.push(await T(K,u));let Ie=y.length,pt=nt(y.map(Ve=>f[Ve].scores))??0;y=ht(f.map((Ve,kr)=>({idx:kr,scores:Ve.scores})),this.tieEpsilon).map(Ve=>Ve.idx);let Ke=nt(y.map(Ve=>f[Ve].scores))??0;(y.length>Ie||Ke>pt+1e-6)&&(b=0),this.mergesDue-=1,this.totalMergesTested+=1,C.add(`${Math.min(G,j)}|${Math.max(G,j)}|${D}`)}continue}}let O=Tr(_,M,()=>this.rand());this.lastIterFoundNewProgram=!1;let E=this.minibatch?this.nextMinibatchIndices(p.length,w).map(V=>p[V]):p;if(r?.skipPerfectScore??!0){let V=Number(r?.perfectScore??1),ne=await T(f[O].cfg,E);if(ne.length>0&&ne.every(B=>B>=V))continue}let $=!1,N={...f[O].cfg},L="reflective_mutation",U=w%a.length,H=a[U],W,ue;if($&&this.mergesUsed<this.mergeMax){let V=(O+1)%f.length,ne=G=>{let j=[],D=G;for(;D!==void 0;)j.push(D),D=f[D]?.parent;return j},B=ne(O),z=ne(V),Z=B.find(G=>z.includes(G)),re=!0;if(Z||(re=!1),(z.includes(O)||B.includes(V))&&(re=!1),re){let G=f[Z].cfg,j=f[O].cfg,D=f[V].cfg,K=!1,ee=new Set([...Object.keys(G),...Object.keys(j),...Object.keys(D)]);for(let fe of ee){let te=G[fe],se=j[fe],ce=D[fe];if(se===te&&ce!==se||ce===te&&se!==ce){K=!0;break}}K||(re=!1)}if(re){let G=Math.min(O,V),j=Math.max(O,V),D=`${G}|${j}|${Z}`;if(!C.has(D)){let K=x(f[Z].scores),ee=x(f[O].scores),fe=x(f[V].scores);K<=Math.min(ee,fe)&&(N=this.systemAwareMerge(f,O,V,(te,se)=>{let ce=x(f[te].scores),ge=x(f[se].scores);return ce>=ge?te:se}),L="system_merge",this.mergesUsed+=1,C.add(D))}}else{let G=f[O].cfg[H.name],j=r?.gepaAdapter,D;if(j)try{let K=await j.evaluate(E,{...f[O].cfg},!0);W=Array.isArray(K?.scores)?K.scores.reduce((se,ce)=>se+(Number(ce)||0),0):void 0;let ee=j.make_reflective_dataset({...f[O].cfg},K,[H.name]),te=(await j.propose_new_texts?.({...f[O].cfg},ee,[H.name]))?.[H.name];typeof te=="string"&&te.length>0&&(D=te)}catch{}if(D||(D=await this.reflectModuleInstruction(H.name,G,s,a,{...f[O].cfg},E,async({prediction:K,example:ee})=>{let fe=await n({prediction:K,example:ee}),te=Object.values(fe||{});return te.length?te.reduce((se,ce)=>se+ce,0)/te.length:0},r)),N[H.name]=D,j&&W!==void 0)try{let K=await j.evaluate(E,N,!1);ue=Array.isArray(K?.scores)?K.scores.reduce((ee,fe)=>ee+(Number(fe)||0),0):void 0}catch{}}}else{let V=f[O].cfg[H.name],ne=r?.gepaAdapter,B;if(ne)try{let z=await ne.evaluate(E,{...f[O].cfg},!0);W=Array.isArray(z?.scores)?z.scores.reduce((j,D)=>j+(Number(D)||0),0):void 0;let Z=ne.make_reflective_dataset({...f[O].cfg},z,[H.name]),G=(await ne.propose_new_texts?.({...f[O].cfg},Z,[H.name]))?.[H.name];typeof G=="string"&&G.length>0&&(B=G)}catch{}if(B||(B=await this.reflectModuleInstruction(H.name,V,s,a,{...f[O].cfg},E,async({prediction:z,example:Z})=>{let re=await n({prediction:z,example:Z}),G=Object.values(re||{});return G.length?G.reduce((j,D)=>j+D,0)/G.length:0},r)),N[H.name]=B,ne&&W!==void 0)try{let z=await ne.evaluate(E,N,!1);ue=Array.isArray(z?.scores)?z.scores.reduce((Z,re)=>Z+(Number(re)||0),0):void 0}catch{}}let ae=await T(f[O].cfg,E),me=await T(N,E),le=ae.reduce((V,ne)=>V+ne,0),oe=me.reduce((V,ne)=>V+ne,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,oe,{modules:a.length,mutatedModule:H.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:L,paretoSetSize:u.length},oe,{idx:O},{...r??{},maxIterations:this.numTrials}),!(oe>le+this.tieEpsilon&&(W===void 0||ue===void 0||ue>W+this.tieEpsilon))){if(++b>=this.earlyStoppingTrials)break;continue}let ye=await g(N,u);f.push({cfg:N,parent:O,scores:ye}),A.push(await T(N,u));let ze=y.length,xe=nt(y.map(V=>f[V].scores))??0;y=ht(f.map((V,ne)=>({idx:ne,scores:V.scores})),this.tieEpsilon).map(V=>V.idx);let ke=nt(y.map(V=>f[V].scores))??0;if(y.length>ze||ke>xe+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 v=ht(f.map((w,I)=>({idx:I,scores:w.scores})),this.tieEpsilon),k=v.length>0?Math.max(...v.map(w=>x(w.scores))):0,F=nt(v.map(w=>w.scores));this.stats.convergenceInfo.converged=!0;let R=this.getMergedCustomLabels(r);return this.recordParetoMetrics(v.length,f.length,"GEPA-Flow",F,R),{demos:[],stats:this.stats,bestScore:k,paretoFront:v.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:v.length,hypervolume:F,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,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?Bt(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 s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],u=[];for(let x of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let T=await a({prediction:A,example:x});u.push({input:x,prediction:A,score:typeof T=="number"?T:0})}catch{u.push({input:x,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=$e('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 x of u){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let h="";try{h=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=$e('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 A=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:h,minibatch:u}))?.newInstruction?.trim();if(A&&A.length>16)return A}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,s=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=s[l%s.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 s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=f=>{let x=[],A=f;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of h){let x=u[f],A=p[f],T=d[f];if(A===x&&T!==A)m[f]=T,g.push("j");else if(T===x&&A!==T)m[f]=A,g.push("i");else if(A!==T&&A!==x&&T!==x){let y=r(t,n);m[f]=y===t?A:T,g.push(y===t?"i":"j")}else m[f]=A??T??x,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=[],x=h;for(;x!==void 0;)f.push(x),x=e[x]?.parent;return f},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??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 h of g){let f=u[h],x=p[h],A=d[h];if(x===f&&A!==x)m[h]=A;else if(A===f&&x!==A)m[h]=x;else if(x!==A&&x!==f&&A!==f){let T=r(t,n);m[h]=T===t?x:A}else m[h]=x??A??f}return m}};var os=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 s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),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 ss=class extends qe{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 os(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,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=`
|
|
511
511
|
Analyze this language model program and provide a concise summary of its purpose and structure.
|
|
512
512
|
|
|
513
513
|
Program Signature: ${e.getSignature()}
|
|
@@ -547,7 +547,7 @@ Requirements:
|
|
|
547
547
|
5. Keep it concise but comprehensive
|
|
548
548
|
|
|
549
549
|
Generate a single, well-crafted instruction:
|
|
550
|
-
Instruction:`;try{let m=(await $e('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),s,a;this.programAwareProposer&&(s=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,p=u>=0?l[u]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:o,programSummary:s,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new Mn({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 s=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:s},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...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},c=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let b=0;b<this.numTrials;b++)try{let C=await this.pythonClient.suggestParameters(a),P=C.params.temperature,
|
|
550
|
+
Instruction:`;try{let m=(await $e('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),s,a;this.programAwareProposer&&(s=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,p=u>=0?l[u]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:o,programSummary:s,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new Mn({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 s=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:s},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...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},c=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let b=0;b<this.numTrials;b++)try{let C=await this.pythonClient.suggestParameters(a),P=C.params.temperature,S=C.params.bootstrappedDemos,v=C.params.instruction,k=C.params.labeledExamples,F=this.optimizeTopP?C.params.topP:void 0;if(P===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(C)}`);if(S===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(C)}`);if(v===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(C)}`);if(k===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(C)}`);let R=e.clone();R.setInstruction(v),R.setExamples(this.selectLabeledExamples(t).slice(0,k));let I=!this.minibatch||this.minibatchFullEvalSteps>0&&b%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let O=Math.min(this.minibatchSize,t.length),E=new Set;for(;E.size<O;)E.add(Math.floor(Math.random()*t.length));return Array.from(E).map($=>t[$])})(),_=await this.evaluateConfiguration(R,n,{temperature:P,bootstrappedDemos:S,topP:F},I);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:C.trial_number,value:_}),_>p+this.minImprovementThreshold?(p=_,d={temperature:P,bootstrappedDemos:S,...F!==void 0?{topP:F}:{},trialNumber:C.trial_number},g=0):g+=1,this.currentRound=b+1;let M={temperature:P,bootstrappedDemos:S,...F!==void 0?{topP:F}:{},trialNumber:C.trial_number};if(this.localScoreHistory.push(_),this.localConfigurationHistory.push(M),await this.updateOptimizationProgress(this.currentRound,_,M,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:b+1,totalRounds:this.numTrials,currentScore:_,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:m,totalExamples:t.length}),this.earlyStoppingTrials>0&&g>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:p,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let h=p,f={},x=[];try{let b=await this.pythonClient.getStudyResults(a);if(h=b.best_value||p,f=b.best_params||{},f&&Object.keys(f).length>0){let C=f.bootstrappedDemos||0;C>0&&(x=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),x=x.slice(0,C))}}catch{}let A;try{let C=await $e('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:h,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:f||{}});A={humanExplanation:C.humanExplanation??"",recommendations:C.recommendations??[],performanceAssessment:C.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",h,f,r,A);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=h;let T=new Ce(e.getSignature());f.instruction&&T.setInstruction(f.instruction),x.length>0&&T.setDemos(x),f.temperature&&(T._optimizedModelConfig={temperature:f.temperature});let y=new gt({bestScore:h,stats:this.stats,instruction:f.instruction,demos:x,examples:[],modelConfig:{temperature:f.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(h,x.length),{bestScore:h,demos:x,stats:this.stats,optimizedGen:T,optimizedProgram:y,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
|
|
551
551
|
\u{1F389} MiPRO Optimization Complete!
|
|
552
552
|
`),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
|
|
553
553
|
`),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
|