@ax-llm/ax 14.0.15 → 14.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,17 +1,17 @@
1
- function W({model:i,modelInfo:e,models:t}){let n=t?.find(l=>l.key===i),o=n&&"model"in n?n.model:i,r=e.find(l=>l.name===i);if(r)return r;let s=o.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===s);return a||null}var Eo=(()=>{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 q(){return Eo.randomUUID()}async function ks(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Eo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var en=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),o=0;for(let r=0;r<n.length;r++){let s=n[r];o=(o<<5)-o+s,o=o&o}return Math.abs(o).toString(16).padStart(8,"0")}async digestAsync(){return ks(this.data)}};function pt(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new en}var ut=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
+ function W({model:i,modelInfo:e,models:t}){let n=t?.find(l=>l.key===i),o=n&&"model"in n?n.model:i,r=e.find(l=>l.name===i);if(r)return r;let s=o.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===s);return a||null}var Eo=(()=>{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 B(){return Eo.randomUUID()}async function Ms(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Eo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var en=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),o=0;for(let r=0;r<n.length;r++){let s=n[r];o=(o<<5)-o+s,o=o&o}return Math.abs(o).toString(16).padStart(8,"0")}async digestAsync(){return Ms(this.data)}};function pt(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new en}var ut=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 o of n)o===""?this.processEvent(e):this.parseLine(o)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
4
4
  `)?`
5
5
  `:"")+e.trim();return}let n=e.slice(0,t).trim(),o=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=o;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
6
6
  `)?`
7
- `:"")+o;break;case"id":this.currentEvent.id=o;break;case"retry":{let r=Number.parseInt(o,10);Number.isNaN(r)||(this.currentEvent.retry=r);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var tn=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},ct=class extends TransformStream{constructor(){super(new tn)}};var Es={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Ps=globalThis.TextDecoderStream??ct,j=class extends Error{constructor(t,n,o,r,s={}){super(t);this.url=n;this.requestBody=o;this.responseBody=r;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=q(),this.context=s,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},de=class extends j{constructor(t,n,o,r,s,a){super(`HTTP ${t} - ${n}`,o,r,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},oe=class extends j{constructor(t,n,o,r,s){super(`Network Error: ${t.message}`,n,o,r,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},re=class extends j{constructor(e,t,n,o){super(e,t,n,void 0,o),this.name=this.constructor.name}},Z=class extends j{constructor(t,n,o,r){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...r});this.lastChunk=o;this.name=this.constructor.name}},me=class extends j{constructor(e,t,n,o){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o}),this.name=this.constructor.name}},Te=class extends j{constructor(e,t,n,o){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...o}),this.name=this.constructor.name}},se=class extends j{constructor(e,t,n,o){super("Authentication failed",e,t,n,o),this.name=this.constructor.name}},E=class extends Error{constructor(t,n,o){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=o;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=q()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},V=class extends Error{constructor(t,n,o=!1){super(`${t} not supported by ${n}${o?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=o;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=q()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ee=class extends Error{constructor(t,n,o){super(`Failed to process ${n} during ${o}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=o;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=q()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function Po(i){try{return i.headers.get("content-type")?.includes("application/json")?await i.json():await i.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Fo(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Fs(){return{startTime:Date.now(),retryCount:0}}function _o(i){i.retryCount++,i.lastRetryTime=Date.now()}function Do(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof oe&&!(i instanceof se)}var z=async(i,e)=>{if(i.localCall)return await i.localCall(e,i.stream);if(!i.url)throw new Error("API URL is required when localCall is not provided");let t={...Es,...i.retry},n=i.timeout,o=Fs(),r,s=new URL(i.url),a=`${[s.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${s.search}`,l=new URL(a,s);if(i.corsProxy){let c=l.href;l=new URL(`${i.corsProxy}?url=${encodeURIComponent(c)}`)}let p=q();if(i.validateRequest&&!await i.validateRequest(e))throw new re("Invalid request data",l.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":o.startTime});let u=0;for(;;){let c=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Te(l.href,i.abortSignal.reason,e,{metrics:o});let d=()=>{c.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",d,{once:!0});let m=c.abort.bind(c);c.abort=g=>{i.abortSignal.removeEventListener("abort",d),m(g)}}n&&(r=setTimeout(()=>{c.abort("Request timeout")},n));try{let d=await(i.fetch??fetch)(l,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":u.toString(),...i.headers},body:JSON.stringify(e),signal:c.signal});if(r&&clearTimeout(r),d.status===401||d.status===403){let A=await Po(d);throw new se(l.href,e,A,{metrics:o})}if(d.status>=400&&Do(new Error,d.status,u,t)){let A=Fo(u,t);u++,_o(o),i.span?.addEvent("retry",{attempt:u,delay:A,status:d.status,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(b=>setTimeout(b,A));continue}if(d.status>=400){let A=await Po(d);throw new de(d.status,d.statusText,l.href,e,A,{metrics:o})}if(!i.stream){let A=await d.json();if(i.validateResponse&&!await i.validateResponse(A))throw new re("Invalid response data",l.href,e,{validation:"response"});return i.span?.setAttributes({"response.time":Date.now()-o.startTime,"response.retries":o.retryCount}),A}if(!d.body)throw new re("Response body is null",l.href,e,{metrics:o});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(A){let b=d.body.getReader(),R=new TextDecoder,y="";async function x(){try{for(;;){let{done:T,value:v}=await b.read();if(T){I=!0,A.close();break}y+=R.decode(v,{stream:!0});let k=y.split(`
7
+ `:"")+o;break;case"id":this.currentEvent.id=o;break;case"retry":{let r=Number.parseInt(o,10);Number.isNaN(r)||(this.currentEvent.retry=r);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var tn=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},ct=class extends TransformStream{constructor(){super(new tn)}};var ks={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Es=globalThis.TextDecoderStream??ct,j=class extends Error{constructor(t,n,o,r,s={}){super(t);this.url=n;this.requestBody=o;this.responseBody=r;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=B(),this.context=s,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},de=class extends j{constructor(t,n,o,r,s,a){super(`HTTP ${t} - ${n}`,o,r,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},oe=class extends j{constructor(t,n,o,r,s){super(`Network Error: ${t.message}`,n,o,r,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},re=class extends j{constructor(e,t,n,o){super(e,t,n,void 0,o),this.name=this.constructor.name}},Z=class extends j{constructor(t,n,o,r){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...r});this.lastChunk=o;this.name=this.constructor.name}},me=class extends j{constructor(e,t,n,o){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o}),this.name=this.constructor.name}},Te=class extends j{constructor(e,t,n,o){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...o}),this.name=this.constructor.name}},se=class extends j{constructor(e,t,n,o){super("Authentication failed",e,t,n,o),this.name=this.constructor.name}},E=class extends Error{constructor(t,n,o){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=o;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=B()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},V=class extends Error{constructor(t,n,o=!1){super(`${t} not supported by ${n}${o?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=o;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=B()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ee=class extends Error{constructor(t,n,o){super(`Failed to process ${n} during ${o}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=o;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=B()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function Po(i){try{return i.headers.get("content-type")?.includes("application/json")?await i.json():await i.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Fo(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Ps(){return{startTime:Date.now(),retryCount:0}}function _o(i){i.retryCount++,i.lastRetryTime=Date.now()}function Do(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof oe&&!(i instanceof se)}var q=async(i,e)=>{if(i.localCall)return await i.localCall(e,i.stream);if(!i.url)throw new Error("API URL is required when localCall is not provided");let t={...ks,...i.retry},n=i.timeout,o=Ps(),r,s=new URL(i.url),a=`${[s.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${s.search}`,l=new URL(a,s);if(i.corsProxy){let d=l.href;l=new URL(`${i.corsProxy}?url=${encodeURIComponent(d)}`)}let p=B();if(i.validateRequest&&!await i.validateRequest(e))throw new re("Invalid request data",l.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":o.startTime});let u=0;for(;;){let d=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Te(l.href,i.abortSignal.reason,e,{metrics:o});let c=()=>{d.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",c,{once:!0});let m=d.abort.bind(d);d.abort=g=>{i.abortSignal.removeEventListener("abort",c),m(g)}}n&&(r=setTimeout(()=>{d.abort("Request timeout")},n));try{let c=await(i.fetch??fetch)(l,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":u.toString(),...i.headers},body:JSON.stringify(e),signal:d.signal});if(r&&clearTimeout(r),c.status===401||c.status===403){let A=await Po(c);throw new se(l.href,e,A,{metrics:o})}if(c.status>=400&&Do(new Error,c.status,u,t)){let A=Fo(u,t);u++,_o(o),i.span?.addEvent("retry",{attempt:u,delay:A,status:c.status,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(I=>setTimeout(I,A));continue}if(c.status>=400){let A=await Po(c);throw new de(c.status,c.statusText,l.href,e,A,{metrics:o})}if(!i.stream){let A=await c.json();if(i.validateResponse&&!await i.validateResponse(A))throw new re("Invalid response data",l.href,e,{validation:"response"});return i.span?.setAttributes({"response.time":Date.now()-o.startTime,"response.retries":o.retryCount}),A}if(!c.body)throw new re("Response body is null",l.href,e,{metrics:o});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(A){let I=c.body.getReader(),b=new TextDecoder,y="";async function R(){try{for(;;){let{done:T,value:w}=await I.read();if(T){f=!0,A.close();break}y+=b.decode(w,{stream:!0});let P=y.split(`
12
12
 
13
- `);y=k.pop()||"";for(let P of k){if(!P.trim())continue;let U=P.split(`
14
- `),K="",be="message";for(let B of U)B.startsWith("data: ")?K=B.slice(6):B.startsWith("event: ")&&(be=B.slice(7));if(K){if(K==="[DONE]"){A.close();return}try{let B=JSON.parse(K);m=B,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),console.log("!!!!>>>>>>>>>parsed",B),A.enqueue(B),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount,"sse.event.type":be})}catch(B){i.debug&&console.warn("Skipping non-JSON SSE data:",K,B)}}}}}catch(T){let v=T,k={...o,streamDuration:Date.now()-o.startTime};v.name==="AbortError"||v.message?.includes("aborted")?A.error(new Z(l.href,e,m,{streamMetrics:k})):A.error(new oe(v,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:k}))}finally{b.releaseLock()}}x()}});let f=new TransformStream({transform(A,b){m=A,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),b.enqueue(A),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})}}),I=!1;return new ReadableStream({start(A){let b=d.body.pipeThrough(new Ps).pipeThrough(new ut).pipeThrough(f).getReader();async function R(){try{for(;;){let{done:y,value:x}=await b.read();if(y){I||(I=!0,A.close());break}if(I)break;A.enqueue(x)}}catch(y){let x=y,T={...o,streamDuration:Date.now()-o.startTime};throw x.name==="AbortError"||x.message?.includes("aborted")?A.error(new Z(l.href,e,m,{streamMetrics:T})):x instanceof TypeError&&x.message.includes("cancelled")?A.error(new Z(l.href,e,m,{streamMetrics:T,cancelReason:"Stream cancelled by client"})):A.error(new oe(x,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:T})),x}finally{r&&clearTimeout(r),b.releaseLock()}}R()},cancel(){I=!0}})}catch(d){if(d instanceof Error&&d.name==="AbortError")throw i.abortSignal?.aborted?new Te(l.href,i.abortSignal.reason,e,{metrics:o}):new me(l.href,n||0,e,{metrics:o});if(i.span?.isRecording()&&(i.span.recordException(d),i.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),d instanceof oe&&Do(d,void 0,u,t)){let m=Fo(u,t);u++,_o(o),i.span?.addEvent("retry",{attempt:u,delay:m,error:d.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw d instanceof j&&(d.context.metrics=o),d}finally{r!==void 0&&clearTimeout(r)}}};import{context as hr,SpanKind as fr}from"@opentelemetry/api";var M={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var $=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 Ha=new $,Lo=i=>{console.log(i)},No=(i,e,t)=>{let n=(o,r)=>t&&r&&r in t?t[r](o):o;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
13
+ `);y=P.pop()||"";for(let k of P){if(!k.trim())continue;let F=k.split(`
14
+ `),K="",be="message";for(let z of F)z.startsWith("data: ")?K=z.slice(6):z.startsWith("event: ")&&(be=z.slice(7));if(K){if(K==="[DONE]"){A.close();return}try{let z=JSON.parse(K);m=z,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),A.enqueue(z),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount,"sse.event.type":be})}catch(z){i.debug&&console.warn("Skipping non-JSON SSE data:",K,z)}}}}}catch(T){let w=T,P={...o,streamDuration:Date.now()-o.startTime};w.name==="AbortError"||w.message?.includes("aborted")?A.error(new Z(l.href,e,m,{streamMetrics:P})):A.error(new oe(w,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:P}))}finally{I.releaseLock()}}R()}});let x=new TransformStream({transform(A,I){m=A,g++,o.streamChunks=g,o.lastChunkTime=Date.now(),I.enqueue(A),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})}}),f=!1;return new ReadableStream({start(A){let I=c.body.pipeThrough(new Es).pipeThrough(new ut).pipeThrough(x).getReader();async function b(){try{for(;;){let{done:y,value:R}=await I.read();if(y){f||(f=!0,A.close());break}if(f)break;A.enqueue(R)}}catch(y){let R=y,T={...o,streamDuration:Date.now()-o.startTime};throw R.name==="AbortError"||R.message?.includes("aborted")?A.error(new Z(l.href,e,m,{streamMetrics:T})):R instanceof TypeError&&R.message.includes("cancelled")?A.error(new Z(l.href,e,m,{streamMetrics:T,cancelReason:"Stream cancelled by client"})):A.error(new oe(R,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:T})),R}finally{r&&clearTimeout(r),I.releaseLock()}}b()},cancel(){f=!0}})}catch(c){if(c instanceof Error&&c.name==="AbortError")throw i.abortSignal?.aborted?new Te(l.href,i.abortSignal.reason,e,{metrics:o}):new me(l.href,n||0,e,{metrics:o});if(i.span?.isRecording()&&(i.span.recordException(c),i.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),c instanceof oe&&Do(c,void 0,u,t)){let m=Fo(u,t);u++,_o(o),i.span?.addEvent("retry",{attempt:u,delay:m,error:c.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw c instanceof j&&(c.context.metrics=o),c}finally{r!==void 0&&clearTimeout(r)}}};import{context as hr,SpanKind as fr}from"@opentelemetry/api";var M={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var $=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 ja=new $,Lo=i=>{console.log(i)},No=(i,e,t)=>{let n=(o,r)=>t&&r&&r in t?t[r](o):o;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
15
15
  ${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
16
16
  ${n(i.result??"[No result]","yellowDim")}`;case"user":{let o=`${n("[ USER ]","greenBright")}
17
17
  `;if(typeof i.content=="string")return o+n(i.content,"green");let r=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 o+r.join(`
@@ -21,7 +21,7 @@ ${n(i.result??"[No result]","yellowDim")}`;case"user":{let o=`${n("[ USER ]","gr
21
21
  `,i.functionCalls.forEach((s,a)=>{let l=typeof s.function.params=="string"?s.function.params:JSON.stringify(s.function.params,null,2);r+=n(`${a+1}. ${s.function.name}(${l}) [id: ${s.id}]`,"yellowDim"),a<(i.functionCalls?.length??0)-1&&(r+=`
22
22
  `)}),r+=`
23
23
  `),!i.content&&(!i.functionCalls||i.functionCalls.length===0)&&(r+=n("[No content]","gray")),r}default:return`${n("[ UNKNOWN ]","redBright")}
24
- ${n(JSON.stringify(i),"gray")}`}},$o=(i=Lo)=>{let e=new $,t=e.gray(`${"\u2500".repeat(60)}
24
+ ${n(JSON.stringify(i),"gray")}`}},Go=(i=Lo)=>{let e=new $,t=e.gray(`${"\u2500".repeat(60)}
25
25
  `);return n=>{let o=n,r="";switch(o.name){case"ChatRequestChatPrompt":r=`
26
26
  ${e.blueBright(`[ CHAT REQUEST Step ${o.step} ]`)}
27
27
  ${t}
@@ -80,7 +80,7 @@ ${t}
80
80
  [ CHAT RESPONSE CITATIONS ]`)}
81
81
  `,o.value.forEach(s=>{r+=`${e.white("- ")}${e.cyan(s.title||s.url)}
82
82
  `,s.description&&(r+=` ${e.gray(s.description)}
83
- `)}),r+=t;break}default:r=e.gray(JSON.stringify(o,null,2))}i(r)}},Go=$o(),_s=(i=Lo)=>{let e="\u2500".repeat(60);return t=>{let n=t,o="";switch(n.name){case"ChatRequestChatPrompt":o=`
83
+ `)}),r+=t;break}default:r=e.gray(JSON.stringify(o,null,2))}i(r)}},$o=Go(),Fs=(i=Lo)=>{let e="\u2500".repeat(60);return t=>{let n=t,o="";switch(n.name){case"ChatRequestChatPrompt":o=`
84
84
  [ CHAT REQUEST Step ${n.step} ]
85
85
  ${e}
86
86
  `,n.value.forEach((r,s)=>{o+=No(r),s<n.value.length-1&&(o+=`
@@ -140,23 +140,23 @@ ${e}
140
140
  `,n.value.forEach(r=>{o+=`- ${r.title||r.url}
141
141
  `,r.description&&(o+=` ${r.description}
142
142
  `)}),o+=`${e}
143
- `;break}default:o=JSON.stringify(n,null,2)}i(o)}};var S={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"},te={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"},Uo=(o=>(o.COMPLETION="completion",o.CHAT="chat",o.RERANK="rerank",o.UNKNOWN="unknown",o))(Uo||{}),Bo=(r=>(r.WORKFLOW="workflow",r.TASK="task",r.AGENT="agent",r.TOOL="tool",r.UNKNOWN="unknown",r))(Bo||{});var nn=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()}},dt=class extends TransformStream{constructor(e,t){super(new nn(e,t))}};function mt(i,e){for(let t of e){let n=i.find(o=>o.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var qo=(i,e,t,n)=>{let o=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:o})};var zo=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)},jo=(i,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:i})};function Ho(i,e){let t=new Map;for(let n of i)for(let o of n.results){if(!o)continue;let r=t.get(o.index);r?(o.content&&(r.content=(r.content??"")+o.content),o.thought&&(r.thought=(r.thought??"")+o.thought),o.finishReason&&(r.finishReason=o.finishReason),o.functionCalls&&(r.functionCalls?mt(r.functionCalls,structuredClone(o.functionCalls)):r.functionCalls=structuredClone(o.functionCalls))):(r=structuredClone(o),t.set(o.index,r))}for(let n of t.values()){let o={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(o)}}var Ko=(i,e)=>{e({name:"FunctionResults",value:i})},on=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},Wo=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},Vo=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},Jo=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var Qo=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Yo=(i,e)=>{let t=i.slice(0,3).map(o=>({length:o.length,sample:o.slice(0,5),truncated:o.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},Xo=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var rn=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n);e[t]=o.length>100?o.substring(0,100):o}return e},gt,Zo=i=>{if(gt)return gt;if(i)return gt=Ds(i),gt};var Ds=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)"})}),er=(i,e,t,n,o)=>{try{if(i.latencyHistogram){let r=rn({operation:e,ai_service:n,...o?{model:o}:{}});i.latencyHistogram.record(t,r)}}catch(r){console.warn("Failed to record latency metric:",r)}},tr=(i,e,t,n,o,r,s)=>{let a={operation:e,ai_service:r,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(o,a)},nr=(i,e,t,n)=>{try{if(i.errorCounter){let o=rn({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},or=(i,e,t,n,o)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...o?{model:o}:{}})},rr=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Re=(i,e,t,n,o)=>{try{let r=rn({ai_service:n,...o?{model:o}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...r}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,r),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,r)}catch(r){console.warn("Failed to record token metric:",r)}},sr=(i,e,t,n,o)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...o?{model:o}:{}})},ir=(i,e,t,n,o)=>{let r={function_name:e,...n?{ai_service:n}:{},...o?{model:o}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,r),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,r)},sn=(i,e,t,n,o)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},an=(i,e,t,n,o)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},ar=(i,e,t,n,o)=>{let r={...n?{ai_service:n}:{},...o?{model:o}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,r),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,r)},ln=(i,e,t,n,o)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...o?{model:o}:{}})},lr=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},pr=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},ur=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},cr=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},dr=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},mr=(i,e,t,n,o)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...o?{model:o}:{}})};function gr(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function J(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${gr(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${gr(e.item)}`),new Error(t.join(`
144
- `))}function Ce(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 o=0;o<n.length;o++){let r=n[o];if(!r||typeof r!="object")throw new Error(`User message content item at index ${o} must be an object, received: ${e(r)}`);let s=typeof r=="object"&&r!==null&&"type"in r&&typeof r.type=="string"?r.type:void 0;if(!s)throw new Error(`User message content item at index ${o} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in r&&typeof r.text=="string"?r.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${o} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in r&&typeof r.image=="string"?r.image:void 0,l="mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${o} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${o} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in r&&typeof r.data=="string"?r.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${o} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in r&&typeof r.fileUri=="string",l="data"in r&&typeof r.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${o} must have either 'data' or 'fileUri', received: ${e(r)}`);if(a&&l)throw new Error(`User message file content at index ${o} cannot have both 'data' and 'fileUri', received: ${e(r)}`);if(a){let u=r.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${o} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=r.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${o} data cannot be empty, received: ${e(u)}`)}let p="mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:null;if(!p||p.trim()==="")throw new Error(`User message file content at index ${o} must have a mimeType, received: ${e(p)}`);break}case"url":{let a="url"in r&&typeof r.url=="string"?r.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${o} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${o} 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,o=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,r=typeof n=="string"&&n.trim()!=="",s=Array.isArray(o)&&o.length>0;if(!r&&!s&&J("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:o},item:i}),n!==void 0&&typeof n!="string"&&J("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),o!==void 0&&!Array.isArray(o)&&J("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:o,item:i}),Array.isArray(o))for(let a=0;a<o.length;a++){let l=o[a];if((!l||typeof l!="object")&&J("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:i}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&J("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:i}),(!("type"in l)||l.type!=="function")&&J("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:i}),!("function"in l)||!l.function)J("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:i});else{let p=l.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&J("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&J("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let a=i.name;(typeof a!="string"||a.trim()==="")&&J("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,o=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(o==null)throw new Error(`Function message must have a result, received: ${e(o)}`);if(typeof o!="string")throw new Error(`Function message result must be a string, received: ${e(o)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&J("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 pn(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 o=t[n];if(!o)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(o)}`);if(typeof o.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(o.index)}`);if(o.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(o.index)}`);if(!o.content&&!o.thought&&!o.functionCalls&&!o.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:o.content,thought:o.thought,functionCalls:o.functionCalls,finishReason:o.finishReason})}`);if(o.content!==void 0&&typeof o.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(o.content)}`);if(o.thought!==void 0&&typeof o.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(o.thought)}`);if(o.name!==void 0){if(typeof o.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(o.name)}`);if(o.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(o.name)}`)}if(o.annotations!==void 0){if(!Array.isArray(o.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(o.annotations)}`);for(let r=0;r<o.annotations.length;r++){let s=o.annotations[r];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${r}] 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}[${r}] 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}[${r}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(o.id!==void 0){if(typeof o.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(o.id)}`);if(o.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(o.id)}`)}if(o.functionCalls!==void 0){if(!Array.isArray(o.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(o.functionCalls)}`);for(let r=0;r<o.functionCalls.length;r++){let s=o.functionCalls[r];if(!s)throw new Error(`Function call at index ${r} 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 ${r} 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 ${r} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${r} 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 ${r} 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 ${r} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(o.finishReason!==void 0){let r=["stop","length","function_call","content_filter","error"];if(!r.includes(o.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${r.join(", ")}, received: ${e(o.finishReason)}`)}}}var O=()=>structuredClone({temperature:0}),L=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),_=class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:r,defaults:s,options:a={},supportFor:l,models:p}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=o,this.supportFor=l,this.tracer=a.tracer??M.tracer,this.meter=a.meter??M.meter,this.modelInfo=r,this.models=p,this.id=q();let u=this.getModel(s.model)??s.model,c=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:c},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),p&&Ns(p)}debug=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=M.logger??Go;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Zo(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=e.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??M.tracer,this.meter=e.meter??M.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??M.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((r,s)=>r-s),o=Math.ceil(t/100*n.length)-1;return n[o]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((r,s)=>r+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;er(o,e,t,this.name,r),tr(o,e,n.mean,n.p95,n.p99,this.name,r)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;rr(o,e,this.name,r),t&&nr(o,e,this.name,r),or(o,e,n.rate,this.name,r)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:o,totalTokens:r,thoughtsTokens:s}=e.tokens;n&&Re(t,"input",n,this.name,e.model),o&&Re(t,"output",o,this.name,e.model),r&&Re(t,"total",r,this.name,e.model),s&&Re(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let r of o.content)r.type==="image"?t=!0:r.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let o of n.content)o.type==="text"&&(t+=o.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(o=>o.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*s/1e6+r*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*s/1e6+r*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&ir(n,o.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ur(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;cr(t,e,this.name,n)}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments();if(!o)return;let r=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;sr(o,"chat",a,this.name,r);let{hasImages:l,hasAudio:p}=this.detectMultimodalContent(e);mr(o,l,p,this.name,r);let u=this.calculatePromptLength(e);lr(o,u,this.name,r),ar(o,s?.temperature,s?.maxTokens,this.name,r),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&dr(o,this.modelUsage.tokens.thoughtsTokens,this.name,r);let c=this.calculateRequestSize(e);if(sn(o,"chat",c,this.name,r),n&&!a){let d=n,m=this.calculateResponseSize(d);if(an(o,"chat",m,this.name,r),d.results)for(let f of d.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&pr(o,g,this.name,r);let h=this.estimateCost(this.lastUsedChatModel,d.modelUsage);h>0&&ln(o,"chat",h,this.name,r)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let o=this.lastUsedEmbedModel,r=this.calculateRequestSize(e);sn(n,"embed",r,this.name,o);let s=this.calculateResponseSize(t);an(n,"embed",s,this.name,o);let a=this.estimateCostByName(o,t.modelUsage);a>0&&ln(n,"embed",a,this.name,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),o=!1,r,s=this.getModelByKey(e.model),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return r=await this._chat1(e,a),r}catch(l){throw o=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("chat")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("chat",l),this.updateErrorMetrics("chat",o),o||this.recordChatMetrics(e,a,r)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let p of e.chatPrompt)Ce(p);let o=this.getModelByKey(e.model),r={...this.aiImpl.getModelConfig(),...o?o.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(p=>p.name===n);if(s?.notSupported?.temperature&&"temperature"in r&&delete r.temperature,s?.notSupported?.topP&&"topP"in r&&delete r.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(p=>p.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return r.stream=(t?.stream!==void 0?t.stream:r.stream)??!0,this.getFeatures(n).streaming||(r.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:fr.SERVER,attributes:{[S.LLM_SYSTEM]:this.name,[S.LLM_OPERATION_NAME]:"chat",[S.LLM_REQUEST_MODEL]:n,[S.LLM_REQUEST_MAX_TOKENS]:r.maxTokens??"Not set",[S.LLM_REQUEST_TEMPERATURE]:r.temperature,[S.LLM_REQUEST_TOP_P]:r.topP??"Not set",[S.LLM_REQUEST_TOP_K]:r.topK??"Not set",[S.LLM_REQUEST_FREQUENCY_PENALTY]:r.frequencyPenalty??"Not set",[S.LLM_REQUEST_PRESENCE_PENALTY]:r.presencePenalty??"Not set",[S.LLM_REQUEST_STOP_SEQUENCES]:r.stopSequences?.join(", ")??"Not set",[S.LLM_REQUEST_LLM_IS_STREAMING]:r.stream??"Not set"}},t?.traceContext??hr.active(),async p=>await this._chat2(n,r,e,t,p)):await this._chat2(n,r,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,o,r){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=o?.debug??this.debug,a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let p=async()=>{let[m,g]=await this.aiImpl.createChatReq(l,o);return r?.isRecording()&&Ls(n,r,this.excludeContentFromTrace),await z({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:s,fetch:this.fetch,span:r,abortSignal:o?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},g)};s&&qo(l.chatPrompt,o?.stepIndex??0,o?.logger??this.logger,o?.debugHideSystemPrompt);let u=o?.rateLimiter??this.rt,c=u?await u(p,{modelUsage:this.modelUsage}):await p();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),g=A=>b=>{let R=m(b,A);if(R.sessionId=o?.sessionId,!R.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(R.modelUsage={ai:this.name,model:e,tokens:y})}if(this.modelUsage=R.modelUsage,this.recordTokenUsage(R.modelUsage),r?.isRecording()&&Ar(R,r,this.excludeContentFromTrace),s)for(let y of R.results)jo(y,y.index,o?.logger??this.logger);return R},h=async A=>{r?.isRecording()&&r.end(),s&&Ho(A,o?.logger??this.logger)};if(typeof window<"u"){let A=c,b={},R=[],y=o?.abortSignal??this.abortSignal;return new ReadableStream({start:x=>{let T=A.getReader(),v=()=>{try{T.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{r?.isRecording()&&r.end()}catch{}try{x.error(new DOMException("Aborted","AbortError"))}catch{x.error(new Error("Aborted"))}};if(y){if(y.aborted){v();return}y.addEventListener("abort",v,{once:!0})}async function k(){try{for(;;){let{done:P,value:U}=await T.read();if(P){h&&await h(R),x.close();break}let K=g(b)(U);K&&(R.push(K),x.enqueue(K))}}catch(P){if(x.error(P),r?.isRecording())try{r.end()}catch{}}finally{if(T.releaseLock(),y)try{y.removeEventListener("abort",v)}catch{}}}k()}})}return c.pipeThrough(new dt(g({}),h))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let d=this.aiImpl.createChatResp(c);if(d.sessionId=o?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return d.modelUsage&&(this.modelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage)),r?.isRecording()&&(Ar(d,r,this.excludeContentFromTrace),r.end()),s&&zo(d,o?.logger??this.logger),d}async embed(e,t){let n=performance.now(),o=!1,r,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 r=await this._embed1(e,a),r}catch(l){throw o=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",o),!o&&r&&this.recordEmbedMetrics(e,r)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:fr.SERVER,attributes:{[S.LLM_SYSTEM]:this.name,[S.LLM_OPERATION_NAME]:"embeddings",[S.LLM_REQUEST_MODEL]:n}},t?.traceContext??hr.active(),async o=>await this._embed2(n,e,t,o)):await this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let r=this.aiImpl.createEmbedReq,s=n?.debug??this.debug,a={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&Qo(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,m]=await r(a);return await z({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:s,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},p=n?.rateLimiter??this.rt,u=p?await p(l,{modelUsage:this.embedModelUsage}):await l(),c=this.aiImpl.createEmbedResp?.(u);if(c.sessionId=n?.sessionId,!c.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(c.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=c.modelUsage,this.recordTokenUsage(c.modelUsage),o?.isRecording()&&c.modelUsage?.tokens&&o.addEvent(te.GEN_AI_USAGE,{[S.LLM_USAGE_INPUT_TOKENS]:c.modelUsage.tokens.promptTokens,[S.LLM_USAGE_OUTPUT_TOKENS]:c.modelUsage.tokens.completionTokens??0,[S.LLM_USAGE_TOTAL_TOKENS]:c.modelUsage.tokens.totalTokens}),s&&Yo(c.embeddings,n?.logger??this.logger),o?.end(),c}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function Ls(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let r of i.chatPrompt)switch(r.role){case"system":if(r.content){let s={};t||(s.content=r.content),e.addEvent(te.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof r.content=="string")n.push(r.content);else if(Array.isArray(r.content))for(let s of r.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=r.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&&r.content&&(a.content=r.content),e.addEvent(te.GEN_AI_ASSISTANT_MESSAGE,a)}else if(r.content){let a={};t||(a.content=r.content),e.addEvent(te.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:r.functionId};t||(s.content=r.result),e.addEvent(te.GEN_AI_TOOL_MESSAGE,s);break}}let o={};t||(o.content=n.join(`
145
- `)),e.addEvent(te.GEN_AI_USER_MESSAGE,o)}function Ar(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[S.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(te.GEN_AI_USAGE,{[S.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[S.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[S.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let o=i.results[n];if(!o||!o.content&&!o.thought&&!o.functionCalls?.length&&!o.finishReason)continue;let r=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};r&&r.length>0?(t||(s.content=o.content),s.tool_calls=r):t||(s.content=o.content??""),e.addEvent(te.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function xr(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 Ns(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 ht=(c=>(c.Claude41Opus="claude-opus-4-1-20250805",c.Claude4Opus="claude-opus-4-20250514",c.Claude4Sonnet="claude-sonnet-4-20250514",c.Claude37Sonnet="claude-3-7-sonnet-latest",c.Claude35Sonnet="claude-3-5-sonnet-latest",c.Claude35Haiku="claude-3-5-haiku-latest",c.Claude3Opus="claude-3-opus-latest",c.Claude3Sonnet="claude-3-sonnet-20240229",c.Claude3Haiku="claude-3-haiku-20240307",c.Claude21="claude-2.1",c.ClaudeInstant12="claude-instant-1.2",c))(ht||{}),un=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(un||{});var ft=[{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var At=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,At(n)]))),e.items&&(e.items=At(e.items)),e},Ir=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...O()}),$s=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...O()}),cn=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=e.modelConfig?.stream??this.config.stream,r;this.isVertex?r={name:o?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:r={name:"/messages"};let 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.filter(x=>x.role==="system").map(x=>({type:"text",text:x.content,...x.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(x=>x.role!=="system"),p=Gs(l),u=e.functions?.map(x=>({name:x.name,description:x.description,input_schema:x.parameters?At(x.parameters):void 0})),d=(this.config.tools??[]).map(x=>x&&typeof x=="object"&&"type"in x?x:{name:x.name,description:x.description,input_schema:x.input_schema?At(x.input_schema):void 0,...x.cache_control?{cache_control:x.cache_control}:{}}),m=[...u??[],...d];this.isVertex&&m.length>0&&(m=m.filter(x=>!(x&&typeof x=="object"&&"type"in x))),m.length===0&&(m=void 0);let g=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,f=e.modelConfig?.temperature,I=e.modelConfig?.topP,A=e.modelConfig?.topK??this.config.topK,b=e.modelConfig?.n??this.config.n;if(b&&b>1)throw new Error("Anthropic does not support sampling (n > 1)");let R;if(this.config.thinking?.budget_tokens&&(R=this.config.thinking),t?.thinkingTokenBudget){let x=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":R=void 0;break;case"minimal":R={type:"enabled",budget_tokens:x?.minimal??1024};break;case"low":R={type:"enabled",budget_tokens:x?.low??5e3};break;case"medium":R={type:"enabled",budget_tokens:x?.medium??1e4};break;case"high":R={type:"enabled",budget_tokens:x?.high??2e4};break;case"highest":R={type:"enabled",budget_tokens:x?.highest??32e3};break}}let y={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...g?{max_tokens:g}:{},...h&&h.length>0?{stop_sequences:h}:{},...f!==void 0&&!R?{temperature:f}:{},...I!==void 0&&(!R||I>=.95)?{top_p:I}:{},...A&&!R?{top_k:A}:{},...s,...m?{tools:m}:{},...o?{stream:!0}:{},...a?{system:a}:{},...R?{thinking:R}:{},messages:p};return[r,y]};createChatResp=e=>{if(e.type==="error")throw new E(e.error.message,void 0,void 0);let t=yr(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,o="",r="",s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(o+=u.text??"",Array.isArray(u.citations))for(let c of u.citations)c?.url&&a.push({url:String(c.url),title:typeof c.title=="string"?c.title:void 0,snippet:typeof c.cited_text=="string"?c.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(r+=u.thinking??"");break;case"tool_use":s.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};o&&(l.content=o),r&&(l.thought=r),s.length>0&&(l.functionCalls=s),a.length>0&&(l.citations=a);let p=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:p,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:r}=e;throw new E(r.message,void 0,void 0)}let o=0;if(e.type==="message_start"){let{message:r}=e,s=[{index:o,content:"",id:r.id}];return this.tokensUsed={promptTokens:r.usage?.input_tokens??0,completionTokens:r.usage?.output_tokens??0,totalTokens:(r.usage?.input_tokens??0)+(r.usage?.output_tokens??0)},{results:s}}if(e.type==="content_block_start"){let{content_block:r}=e;if(r.type==="text"){let s=[];if(Array.isArray(r.citations))for(let a of r.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:o,content:r.text,...s.length?{citations:s}:{}}]}}if(r.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="tool_use"&&typeof r.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=r.id;let s=[{id:r.id,type:"function",function:{name:r.name,params:""}}];return{results:[{index:o,functionCalls:s}]}}if(r.type==="web_search_tool_result"||r.type==="server_tool_use")return{results:[{index:o,content:""}]}}if(e.type==="content_block_delta"){let{delta:r}=e;if(r.type==="citations_delta"){let s=r.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:o,content:"",citations:a}]}}return{results:[{index:o,content:""}]}}if(r.type==="text_delta"){let s=[];if(Array.isArray(r.citations))for(let a of r.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:o,content:r.text,...s.length?{citations:s}:{}}]}}if(r.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="signature_delta")return{results:[{index:o,content:""}]};if(r.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:o,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:r.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:r,usage:s}=e;return this.tokensUsed={promptTokens:0,completionTokens:s.output_tokens,totalTokens:s.output_tokens},{results:[{index:o,content:"",finishReason:yr(r.stop_reason)}]}}return{results:[{index:o,content:""}]}}},we=class i extends _{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:o,options:r,models:s}){let a=t!==void 0&&n!==void 0,l,p;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,p=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",p=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let u={...Ir(),...o},c=new cn(u,a),d=m=>{let g=W({model:m,modelInfo:ft,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:g?.supported?.thinkingBudget??!1,multiTurn:!0}};super(c,{name:"Anthropic",apiURL:l,headers:p,modelInfo:ft,defaults:{model:u.model},options:r,supportFor:d,models:s})}};function Gs(i){let e=i.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(o=>{let r={};return typeof o.function.params=="string"?r=JSON.parse(o.function.params):typeof o.function.params=="object"&&(r=o.function.params),{type:"tool_use",id:o.id,name:o.function.name,input:r,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return Us(e)}function Us(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 o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function yr(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 xt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",y.O1="o1",y.O1Mini="o1-mini",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(xt||{}),Se=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Se||{});var ve=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1Pro="o1-pro",T.O1="o1",T.O1Mini="o1-mini",T.O3Pro="o3-pro",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(ve||{});var Oe=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],dn=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Bs=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},ge=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...O()}),gn=()=>structuredClone({...ge(),model:"gpt-5"}),hn=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...L()}),fn=()=>({...ge(),model:"gpt-5-nano"}),mn=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq(e,t){let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o={name:"/chat/completions"},r=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=qs(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,p=e.modelConfig?.stream??this.config.stream,u=this.config.store,c=Bs(n),d={model:n,messages:a,...this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...r?{tools:r}:{},...s?{tool_choice:s}:{},...c?{}:{...(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}:{},...p&&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}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[o,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"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}createChatResp(e){let{id:t,usage:n,choices:o,error:r}=e;if(r)throw r;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:o.map(a=>{if(a.message.refusal)throw new E(a.message.refusal,e.model,e.id);let l=br(a.finish_reason),p=a.message.tool_calls?.map(({id:u,function:{arguments:c,name:d}})=>({id:u,type:"function",function:{name:d,params:c}}));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:p,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:o,choices:r}=e;this.tokensUsed=o?{promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:r.map(({index:l,delta:{content:p,role:u,refusal:c,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(c)throw new E(c,void 0,n);let f=br(h),I=d?.map(({id:A,index:b,function:{name:R,arguments:y}})=>{typeof A=="string"&&typeof b=="number"&&!s.indexIdMap[b]&&(s.indexIdMap[b]=A);let x=s.indexIdMap[b];return x?{id:x,type:"function",function:{name:R,params:y}}:null}).filter(A=>A!==null);return{index:l,content:p??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:I,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(o=>o.embedding)}}},br=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function qs(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(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.image}`,details:o.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:o.data,format:o.format==="wav"?"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(o=>({id:o.id,type:"function",function:{name:o.function.name,arguments:typeof o.function.params=="object"?JSON.stringify(o.function.params):o.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var F=class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new mn(t,n?.streamingUsage??!0,a);super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},Me=class extends F{constructor({apiKey:e,apiURL:t,config:n,options:o,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Oe,...s??[]];let a=l=>{let p=W({model:l,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:p?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,apiURL:t,config:{...ge(),...n},options:o,modelInfo:s,models:r,supportFor:a}),super.setName("OpenAI")}};var Tr=ge,zs=hn,js=fn,Hs=gn,ke=class extends F{constructor({apiKey:e,resourceName:t,deploymentName:n,version:o="api-version=2024-02-15-preview",config:r,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 p={...Tr(),...r};l=[...Oe,...l??[]];let u=d=>{let m=W({model:d,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:p,options:s,models:a,modelInfo:l,supportFor:u});let c=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${o}`,c).href),super.setHeaders(async()=>({"api-key":e}))}};var An=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.");Ks(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(),o=t.getMetrics();return n.latency.chat.mean-o.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,o=Date.now()-n,r=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return o>=r}handleFailure(){let t=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof j))throw n;switch(n.constructor){case se:throw n;case de:break;case oe:break;case re:break;case Z:break;case me:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Ks(i){let e=i.find(o=>o.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(o=>o.key));for(let o=0;o<i.length;o++){let r=i[o];if(!r)throw new Error(`Service at index ${o} is undefined`);let s=r.getModelList();if(!s)throw new Error(`Service at index ${o} (${r.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 ${o} (${r.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${o} (${r.getName()}) has extra model "${l}"`)}}function he(i){let e=!1,t=!1,n=!1,o=!1,r=!1,s=!1,a=!1,l=new Set,p=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let c of u.content)switch(l.add(c.type),c.type){case"image":e=!0,c.cache&&(a=!0),p+=85;break;case"audio":t=!0,c.cache&&(a=!0),p+=c.duration||60;break;case"file":n=!0,c.cache&&(a=!0),p+=Math.ceil((c.extractedText?.length||1e3)/4);break;case"url":o=!0,c.cache&&(a=!0),p+=Math.ceil((c.cachedContent?.length||2e3)/4);break;case"text":c.cache&&(a=!0),p+=Math.ceil(c.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(p+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(r=!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&&(o=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:o,requiresFunctions:r,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:p}}function Rr(i,e){let t=i.getFeatures(),n=[],o=[],r=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),r.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),r.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),r.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),r.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),r.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),r.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&o.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&&o.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:o,alternatives:r}}function xn(i,e){return i.map(t=>{let n=t.getFeatures(),o=Rr(t,e),r=0,s=[];return r+=10,e.hasImages&&n.media.images.supported&&(r+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(r+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(r+=3)),e.hasAudio&&n.media.audio.supported&&(r+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(r+=5)),e.hasFiles&&n.media.files.supported&&(r+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(r+=3)),e.hasUrls&&n.media.urls.supported&&(r+=25,s.push("URLs"),n.media.urls.webSearch&&(r+=5)),e.requiresFunctions&&n.functions&&(r+=15,s.push("Functions"),n.functionCot&&(r+=3)),e.requiresStreaming&&n.streaming&&(r+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(r+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(r+=3)),n.thinking&&(r+=2),n.multiTurn&&(r+=2),n.hasThinkingBudget&&(r+=1),n.hasShowThoughts&&(r+=1),r-=o.missingCapabilities.length*10,{provider:t,score:r,missingCapabilities:o.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function yn(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=he(i),o=xn(e,n);if(t.requireExactMatch){let r=o.filter(s=>s.missingCapabilities.length===0);if(r.length===0)throw new Error(`No providers fully support the request requirements: ${o[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return r[0].provider}if(!t.allowDegradation){let r=o[0];if(r.missingCapabilities.length>0)throw new Error(`Best available provider (${r.provider.getName()}) is missing: ${r.missingCapabilities.join(", ")}`)}return o[0].provider}function Ws(i,e){let t=he(i),n=xn(e,t),o=n[0]?.provider||null,r=[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=o?n[0].supportedCapabilities.length:0,a=o?`${o.getName()} supports ${s}/${r} requirements (${Math.round(s/Math.max(r,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:o,summary:a}}function Vs(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Js(i,e){let t={};for(let n of i){let r=n.getFeatures().media[e];if(r.supported)for(let s of r.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var yt=(o=>(o.CommandRPlus="command-r-plus",o.CommandR="command-r",o.Command="command",o.CommandLight="command-light",o))(yt||{}),It=(o=>(o.EmbedEnglishV30="embed-english-v3.0",o.EmbedEnglishLightV30="embed-english-light-v3.0",o.EmbedMultiLingualV30="embed-multilingual-v3.0",o.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",o))(It||{});var In=[{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 wr=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...O()}),Qs=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...L()}),bn=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),o=e.chatPrompt.slice(0,-1),r;n&&n.role==="user"&&typeof n.content=="string"&&(r=n?.content);let s=Ys(o),a=e.functions?.map(c=>{let d={};if(c.parameters?.properties)for(let[m,g]of Object.entries(c.parameters.properties))d[m]={description:g.description,type:g.type,required:c.parameters.required?.includes(m)??!1};return{name:c.name,description:c.description,parameter_definitions:d}}),l=e.chatPrompt.filter(c=>c.role==="function").map(c=>{let d=a?.find(m=>m.name===c.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:c.result??""}]}}),p={name:"/chat"},u={message:r,model:t,tools:a,...l&&!r?{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[p,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"},o={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,o]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(r=>({id:r.name,type:"function",function:{name:r.name,params:r.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:o}=this.createChatResp(e),r=o[0];if(!r)throw new Error("No result");return r.id=n.generation_id??"",{results:o}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Ee=class extends _{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("Cohere API key not set");let r={...wr(),...t},s=new bn(r);super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:In,defaults:{model:r.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:o})}};function Ys(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=Cr(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),o=Cr(n)?.at(0);if(!o)throw new Error("Function call not found");let r=[{result:e.result}];return{role:"TOOL",tool_results:[{call:o,outputs:r}]}}default:throw new Error("Unknown role")}})}function Cr(i){return i?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var bt=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(bt||{});var Tn=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Sr=()=>structuredClone({model:"deepseek-chat",...O()}),Xs=()=>structuredClone({model:"deepseek-coder",...L()}),Pe=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...Sr(),...t};r=[...Tn,...r??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:r,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:o}),super.setName("DeepSeek")}};var Tt=(u=>(u.Gemini25Pro="gemini-2.5-pro",u.Gemini25Flash="gemini-2.5-flash",u.Gemini25FlashLite="gemini-2.5-flash-lite",u.Gemini20Flash="gemini-2.0-flash",u.Gemini20FlashLite="gemini-2.0-flash-lite",u.Gemini1Pro="gemini-1.0-pro",u.Gemini15Flash="gemini-1.5-flash",u.Gemini15Flash002="gemini-1.5-flash-002",u.Gemini15Flash8B="gemini-1.5-flash-8b",u.Gemini15Pro="gemini-1.5-pro",u))(Tt||{}),Rn=(o=>(o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(Rn||{}),Cn=(o=>(o.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",o.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",o.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",o.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",o))(Cn||{}),wn=(r=>(r.BlockNone="BLOCK_NONE",r.BlockOnlyHigh="BLOCK_ONLY_HIGH",r.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",r.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",r.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",r))(wn||{}),vr=(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))(vr||{});var Sn=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var vn=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,vn(n)]))),e.items&&(e.items=vn(e.items)),e},Or=[{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"}],Mr=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Or,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...O()}),Zs=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Or,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...L()}),On=class{constructor(e,t,n,o,r){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=o;this.options=r;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,o=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r;if(this.endpointId?r={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:r={name:o?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=o?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;r.name+=`${h}key=${f}`}let s=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(h=>h.role!=="system").map((h,f)=>{switch(h.role){case"user":return{role:"user",parts:Array.isArray(h.content)?h.content.map((A,b)=>{switch(A.type){case"text":return{text:A.text};case"image":return{inlineData:{mimeType:A.mimeType,data:A.image}};case"audio":return{inlineData:{mimeType:`audio/${A.format??"mp3"}`,data:A.data}};case"file":return"fileUri"in A?{fileData:{mimeType:A.mimeType,fileUri:A.fileUri}}:{inlineData:{mimeType:A.mimeType,data:A.data}};default:throw new Error(`Chat prompt content type not supported (index: ${b})`)}}):[{text:h.content}]};case"assistant":{let I=[];if(h.functionCalls){if(I=h.functionCalls.map(A=>{let b=typeof A.function.params=="string"?JSON.parse(A.function.params):A.function.params;return{functionCall:{name:A.function.name,args:b}}}),!I)throw new Error("Function call is empty");return{role:"model",parts:I}}if(!h.content)throw new Error("Assistant content is empty");return I=[{text:h.content}],{role:"model",parts:I}}case"function":{if(!("functionId"in h))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:h.functionId,response:{result:h.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(h)} (index: ${f})`)}}),p=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(f=>({...f,parameters:f.parameters?vn(f.parameters):void 0}));p.push({function_declarations:h})}this.options?.codeExecution&&p.push({code_execution:{}}),this.options?.googleSearchRetrieval&&p.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&p.push({google_search:{}}),this.options?.urlContext&&p.push({url_context:{}}),p.length===0&&(p=void 0);let u;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...h}}else p&&p.length>0&&(u={function_calling_config:{mode:"AUTO"}});let c={};if(this.config.thinking?.includeThoughts&&(c.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(c.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let h=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":c.thinkingBudget=0,c.includeThoughts=!1;break;case"minimal":c.thinkingBudget=h?.minimal??200;break;case"low":c.thinkingBudget=h?.low??800;break;case"medium":c.thinkingBudget=h?.medium??5e3;break;case"high":c.thinkingBudget=h?.high??1e4;break;case"highest":c.thinkingBudget=h?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(c.includeThoughts=t.showThoughts);let d={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(c).length>0?{thinkingConfig:c}:{}},m=this.config.safetySettings;return[r,{contents:l,tools:p,toolConfig:u,systemInstruction:a,generationConfig:d,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,o;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},o={instances:e.texts.map(r=>({content:r,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let r=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${r}`},o={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,o]};createChatResp=e=>{let t=e.candidates?.map(n=>{let o={index:0};switch(n.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new E("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new E("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new E("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new E("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new E("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new E("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new E("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new E("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new E("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return o;for(let s of n.content.parts){if("text"in s){"thought"in s&&s.thought?o.thought=s.text:o.content=s.text;continue}"functionCall"in s&&(o.functionCalls=[{id:q(),type:"function",function:{name:s.functionCall.name,params:s.functionCall.args}}])}let r=n.citationMetadata?.citations;if(Array.isArray(r)&&r.length){let s=a=>a?`${a.year}-${String(a.month).padStart(2,"0")}-${String(a.day).padStart(2,"0")}`:void 0;o.citations=r.filter(a=>typeof a?.uri=="string").map(a=>({url:a.uri,title:a.title,license:a.license,publicationDate:s(a.publicationDate)}))}return o});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Fe=class i extends _{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:o,config:r,options:s,models:a,modelInfo:l}){let p=t!==void 0&&n!==void 0,u,c;if(p){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;o?h="endpoints":h="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,c=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",c=async()=>({})}let d={...Mr(),...r},m=new On(d,p,o,e,s);l=[...Sn,...l??[]];let g=h=>{let f=W({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}};super(m,{name:"GoogleGeminiAI",apiURL:u,headers:c,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:a})}};var ei=new $,_e=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(ei.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 Rt=(o=>(o.Llama3_8B="llama3-8b-8192",o.Llama33_70B="llama-3.3-70b-versatile",o.Mixtral_8x7B="mixtral-8x7b-32768",o.Gemma2_9B="gemma2-9b-it",o))(Rt||{});var Mn=[{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 ti=()=>structuredClone({model:"llama-3.3-70b-versatile",...O()}),De=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Groq API key not set");let s={...ti(),...t},a={...n,streamingUsage:!1};r=[...Mn,...r??[]];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:r,apiURL:"https://api.groq.com/openai/v1",models:o,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new _e(t,t/60,{debug:e?.debug});return async(r,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await r()}}};var kn=[];var En=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(En||{});var kr=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...O()}),ni=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...L()}),Pn=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:
143
+ `;break}default:o=JSON.stringify(n,null,2)}i(o)}};var v={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},te={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"},Uo=(o=>(o.COMPLETION="completion",o.CHAT="chat",o.RERANK="rerank",o.UNKNOWN="unknown",o))(Uo||{}),Bo=(r=>(r.WORKFLOW="workflow",r.TASK="task",r.AGENT="agent",r.TOOL="tool",r.UNKNOWN="unknown",r))(Bo||{});var nn=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()}},dt=class extends TransformStream{constructor(e,t){super(new nn(e,t))}};function mt(i,e){for(let t of e){let n=i.find(o=>o.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var qo=(i,e,t,n)=>{let o=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:o})};var zo=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)},jo=(i,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:i})};function Ho(i,e){let t=new Map;for(let n of i)for(let o of n.results){if(!o)continue;let r=t.get(o.index);r?(o.content&&(r.content=(r.content??"")+o.content),o.thought&&(r.thought=(r.thought??"")+o.thought),o.finishReason&&(r.finishReason=o.finishReason),o.functionCalls&&(r.functionCalls?mt(r.functionCalls,structuredClone(o.functionCalls)):r.functionCalls=structuredClone(o.functionCalls))):(r=structuredClone(o),t.set(o.index,r))}for(let n of t.values()){let o={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(o)}}var Ko=(i,e)=>{e({name:"FunctionResults",value:i})},on=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},Wo=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},Vo=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},Jo=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var Qo=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Yo=(i,e)=>{let t=i.slice(0,3).map(o=>({length:o.length,sample:o.slice(0,5),truncated:o.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},Xo=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var rn=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n);e[t]=o.length>100?o.substring(0,100):o}return e},gt,Zo=i=>{if(gt)return gt;if(i)return gt=_s(i),gt};var _s=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)"})}),er=(i,e,t,n,o)=>{try{if(i.latencyHistogram){let r=rn({operation:e,ai_service:n,...o?{model:o}:{}});i.latencyHistogram.record(t,r)}}catch(r){console.warn("Failed to record latency metric:",r)}},tr=(i,e,t,n,o,r,s)=>{let a={operation:e,ai_service:r,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(o,a)},nr=(i,e,t,n)=>{try{if(i.errorCounter){let o=rn({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},or=(i,e,t,n,o)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...o?{model:o}:{}})},rr=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Re=(i,e,t,n,o)=>{try{let r=rn({ai_service:n,...o?{model:o}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...r}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,r),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,r)}catch(r){console.warn("Failed to record token metric:",r)}},sr=(i,e,t,n,o)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...o?{model:o}:{}})},ir=(i,e,t,n,o)=>{let r={function_name:e,...n?{ai_service:n}:{},...o?{model:o}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,r),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,r)},sn=(i,e,t,n,o)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},an=(i,e,t,n,o)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},ar=(i,e,t,n,o)=>{let r={...n?{ai_service:n}:{},...o?{model:o}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,r),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,r)},ln=(i,e,t,n,o)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...o?{model:o}:{}})},lr=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},pr=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},ur=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},cr=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},dr=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},mr=(i,e,t,n,o)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...o?{model:o}:{}})};function gr(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function J(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${gr(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${gr(e.item)}`),new Error(t.join(`
144
+ `))}function Ce(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 o=0;o<n.length;o++){let r=n[o];if(!r||typeof r!="object")throw new Error(`User message content item at index ${o} must be an object, received: ${e(r)}`);let s=typeof r=="object"&&r!==null&&"type"in r&&typeof r.type=="string"?r.type:void 0;if(!s)throw new Error(`User message content item at index ${o} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in r&&typeof r.text=="string"?r.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${o} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in r&&typeof r.image=="string"?r.image:void 0,l="mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${o} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${o} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in r&&typeof r.data=="string"?r.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${o} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in r&&typeof r.fileUri=="string",l="data"in r&&typeof r.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${o} must have either 'data' or 'fileUri', received: ${e(r)}`);if(a&&l)throw new Error(`User message file content at index ${o} cannot have both 'data' and 'fileUri', received: ${e(r)}`);if(a){let u=r.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${o} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=r.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${o} data cannot be empty, received: ${e(u)}`)}let p="mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:null;if(!p||p.trim()==="")throw new Error(`User message file content at index ${o} must have a mimeType, received: ${e(p)}`);break}case"url":{let a="url"in r&&typeof r.url=="string"?r.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${o} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${o} 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,o=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,r=typeof n=="string"&&n.trim()!=="",s=Array.isArray(o)&&o.length>0;if(!r&&!s&&J("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:o},item:i}),n!==void 0&&typeof n!="string"&&J("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),o!==void 0&&!Array.isArray(o)&&J("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:o,item:i}),Array.isArray(o))for(let a=0;a<o.length;a++){let l=o[a];if((!l||typeof l!="object")&&J("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:i}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&J("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:i}),(!("type"in l)||l.type!=="function")&&J("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:i}),!("function"in l)||!l.function)J("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:i});else{let p=l.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&J("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&J("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let a=i.name;(typeof a!="string"||a.trim()==="")&&J("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,o=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(o==null)throw new Error(`Function message must have a result, received: ${e(o)}`);if(typeof o!="string")throw new Error(`Function message result must be a string, received: ${e(o)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&J("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 pn(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 o=t[n];if(!o)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(o)}`);if(typeof o.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(o.index)}`);if(o.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(o.index)}`);if(!o.content&&!o.thought&&!o.functionCalls&&!o.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:o.content,thought:o.thought,functionCalls:o.functionCalls,finishReason:o.finishReason})}`);if(o.content!==void 0&&typeof o.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(o.content)}`);if(o.thought!==void 0&&typeof o.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(o.thought)}`);if(o.name!==void 0){if(typeof o.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(o.name)}`);if(o.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(o.name)}`)}if(o.annotations!==void 0){if(!Array.isArray(o.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(o.annotations)}`);for(let r=0;r<o.annotations.length;r++){let s=o.annotations[r];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${r}] 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}[${r}] 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}[${r}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(o.id!==void 0){if(typeof o.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(o.id)}`);if(o.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(o.id)}`)}if(o.functionCalls!==void 0){if(!Array.isArray(o.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(o.functionCalls)}`);for(let r=0;r<o.functionCalls.length;r++){let s=o.functionCalls[r];if(!s)throw new Error(`Function call at index ${r} 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 ${r} 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 ${r} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${r} 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 ${r} 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 ${r} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(o.finishReason!==void 0){let r=["stop","length","function_call","content_filter","error"];if(!r.includes(o.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${r.join(", ")}, received: ${e(o.finishReason)}`)}}}var O=()=>structuredClone({temperature:0}),N=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),D=class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:r,defaults:s,options:a={},supportFor:l,models:p}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=o,this.supportFor=l,this.tracer=a.tracer??M.tracer,this.meter=a.meter??M.meter,this.modelInfo=r,this.models=p,this.id=B();let u=this.getModel(s.model)??s.model,d=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:d},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),p&&Ls(p)}debug=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=M.logger??$o;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Zo(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=e.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??M.tracer,this.meter=e.meter??M.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??M.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((r,s)=>r-s),o=Math.ceil(t/100*n.length)-1;return n[o]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((r,s)=>r+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;er(o,e,t,this.name,r),tr(o,e,n.mean,n.p95,n.p99,this.name,r)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;rr(o,e,this.name,r),t&&nr(o,e,this.name,r),or(o,e,n.rate,this.name,r)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:o,totalTokens:r,thoughtsTokens:s}=e.tokens;n&&Re(t,"input",n,this.name,e.model),o&&Re(t,"output",o,this.name,e.model),r&&Re(t,"total",r,this.name,e.model),s&&Re(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let r of o.content)r.type==="image"?t=!0:r.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let o of n.content)o.type==="text"&&(t+=o.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(o=>o.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*s/1e6+r*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*s/1e6+r*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&ir(n,o.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ur(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;cr(t,e,this.name,n)}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments();if(!o)return;let r=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;sr(o,"chat",a,this.name,r);let{hasImages:l,hasAudio:p}=this.detectMultimodalContent(e);mr(o,l,p,this.name,r);let u=this.calculatePromptLength(e);lr(o,u,this.name,r),ar(o,s?.temperature,s?.maxTokens,this.name,r),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&dr(o,this.modelUsage.tokens.thoughtsTokens,this.name,r);let d=this.calculateRequestSize(e);if(sn(o,"chat",d,this.name,r),n&&!a){let c=n,m=this.calculateResponseSize(c);if(an(o,"chat",m,this.name,r),c.results)for(let x of c.results)x.functionCalls&&this.recordFunctionCallMetrics(x.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,c.modelUsage);g>0&&pr(o,g,this.name,r);let h=this.estimateCost(this.lastUsedChatModel,c.modelUsage);h>0&&ln(o,"chat",h,this.name,r)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let o=this.lastUsedEmbedModel,r=this.calculateRequestSize(e);sn(n,"embed",r,this.name,o);let s=this.calculateResponseSize(t);an(n,"embed",s,this.name,o);let a=this.estimateCostByName(o,t.modelUsage);a>0&&ln(n,"embed",a,this.name,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),o=!1,r,s=this.getModelByKey(e.model),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return r=await this._chat1(e,a),r}catch(l){throw o=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("chat")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("chat",l),this.updateErrorMetrics("chat",o),o||this.recordChatMetrics(e,a,r)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let p of e.chatPrompt)Ce(p);let o=this.getModelByKey(e.model),r={...this.aiImpl.getModelConfig(),...o?o.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(p=>p.name===n);if(s?.notSupported?.temperature&&"temperature"in r&&delete r.temperature,s?.notSupported?.topP&&"topP"in r&&delete r.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(p=>p.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return r.stream=(t?.stream!==void 0?t.stream:r.stream)??!0,this.getFeatures(n).streaming||(r.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:fr.SERVER,attributes:{[v.LLM_SYSTEM]:this.name,[v.LLM_OPERATION_NAME]:"chat",[v.LLM_REQUEST_MODEL]:n,[v.LLM_REQUEST_MAX_TOKENS]:r.maxTokens??"Not set",[v.LLM_REQUEST_TEMPERATURE]:r.temperature,[v.LLM_REQUEST_TOP_P]:r.topP??"Not set",[v.LLM_REQUEST_TOP_K]:r.topK??"Not set",[v.LLM_REQUEST_FREQUENCY_PENALTY]:r.frequencyPenalty??"Not set",[v.LLM_REQUEST_PRESENCE_PENALTY]:r.presencePenalty??"Not set",[v.LLM_REQUEST_STOP_SEQUENCES]:r.stopSequences?.join(", ")??"Not set",[v.LLM_REQUEST_LLM_IS_STREAMING]:r.stream??"Not set"}},t?.traceContext??hr.active(),async p=>await this._chat2(n,r,e,t,p)):await this._chat2(n,r,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,o,r){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=o?.debug??this.debug,a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let p=async()=>{let[m,g]=await this.aiImpl.createChatReq(l,o);return r?.isRecording()&&Ds(n,r,this.excludeContentFromTrace),await q({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:s,fetch:this.fetch,span:r,abortSignal:o?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},g)};s&&qo(l.chatPrompt,o?.stepIndex??0,o?.logger??this.logger,o?.debugHideSystemPrompt);let u=o?.rateLimiter??this.rt,d=u?await u(p,{modelUsage:this.modelUsage}):await p();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),g=A=>I=>{let b=m(I,A);if(b.sessionId=o?.sessionId,!b.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(b.modelUsage={ai:this.name,model:e,tokens:y})}if(this.modelUsage=b.modelUsage,this.recordTokenUsage(b.modelUsage),r?.isRecording()&&Ar(b,r,this.excludeContentFromTrace),s)for(let y of b.results)jo(y,y.index,o?.logger??this.logger);return b},h=async A=>{r?.isRecording()&&r.end(),s&&Ho(A,o?.logger??this.logger)};if(typeof window<"u"){let A=d,I={},b=[],y=o?.abortSignal??this.abortSignal;return new ReadableStream({start:R=>{let T=A.getReader(),w=()=>{try{T.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{r?.isRecording()&&r.end()}catch{}try{R.error(new DOMException("Aborted","AbortError"))}catch{R.error(new Error("Aborted"))}};if(y){if(y.aborted){w();return}y.addEventListener("abort",w,{once:!0})}async function P(){try{for(;;){let{done:k,value:F}=await T.read();if(k){h&&await h(b),R.close();break}let K=g(I)(F);K&&(b.push(K),R.enqueue(K))}}catch(k){if(R.error(k),r?.isRecording())try{r.end()}catch{}}finally{if(T.releaseLock(),y)try{y.removeEventListener("abort",w)}catch{}}}P()}})}return d.pipeThrough(new dt(g({}),h))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let c=this.aiImpl.createChatResp(d);if(c.sessionId=o?.sessionId,!c.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(c.modelUsage={ai:this.name,model:e,tokens:m})}return c.modelUsage&&(this.modelUsage=c.modelUsage,this.recordTokenUsage(c.modelUsage)),r?.isRecording()&&(Ar(c,r,this.excludeContentFromTrace),r.end()),s&&zo(c,o?.logger??this.logger),c}async embed(e,t){let n=performance.now(),o=!1,r,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 r=await this._embed1(e,a),r}catch(l){throw o=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",o),!o&&r&&this.recordEmbedMetrics(e,r)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:fr.SERVER,attributes:{[v.LLM_SYSTEM]:this.name,[v.LLM_OPERATION_NAME]:"embeddings",[v.LLM_REQUEST_MODEL]:n}},t?.traceContext??hr.active(),async o=>await this._embed2(n,e,t,o)):await this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let r=this.aiImpl.createEmbedReq,s=n?.debug??this.debug,a={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&Qo(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[c,m]=await r(a);return await q({name:c.name,url:this.apiURL,localCall:c.localCall,headers:await this.buildHeaders(c.headers),debug:s,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},p=n?.rateLimiter??this.rt,u=p?await p(l,{modelUsage:this.embedModelUsage}):await l(),d=this.aiImpl.createEmbedResp?.(u);if(d.sessionId=n?.sessionId,!d.modelUsage){let c=this.aiImpl.getTokenUsage();c&&(d.modelUsage={ai:this.name,model:e,tokens:c})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),o?.isRecording()&&d.modelUsage?.tokens&&o.addEvent(te.GEN_AI_USAGE,{[v.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[v.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[v.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Yo(d.embeddings,n?.logger??this.logger),o?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function Ds(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let r of i.chatPrompt)switch(r.role){case"system":if(r.content){let s={};t||(s.content=r.content),e.addEvent(te.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof r.content=="string")n.push(r.content);else if(Array.isArray(r.content))for(let s of r.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=r.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&&r.content&&(a.content=r.content),e.addEvent(te.GEN_AI_ASSISTANT_MESSAGE,a)}else if(r.content){let a={};t||(a.content=r.content),e.addEvent(te.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:r.functionId};t||(s.content=r.result),e.addEvent(te.GEN_AI_TOOL_MESSAGE,s);break}}let o={};t||(o.content=n.join(`
145
+ `)),e.addEvent(te.GEN_AI_USER_MESSAGE,o)}function Ar(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[v.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(te.GEN_AI_USAGE,{[v.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[v.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[v.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let o=i.results[n];if(!o||!o.content&&!o.thought&&!o.functionCalls?.length&&!o.finishReason)continue;let r=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};r&&r.length>0?(t||(s.content=o.content),s.tool_calls=r):t||(s.content=o.content??""),e.addEvent(te.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function xr(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 Ls(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 ht=(d=>(d.Claude41Opus="claude-opus-4-1-20250805",d.Claude4Opus="claude-opus-4-20250514",d.Claude4Sonnet="claude-sonnet-4-20250514",d.Claude37Sonnet="claude-3-7-sonnet-latest",d.Claude35Sonnet="claude-3-5-sonnet-latest",d.Claude35Haiku="claude-3-5-haiku-latest",d.Claude3Opus="claude-3-opus-latest",d.Claude3Sonnet="claude-3-sonnet-20240229",d.Claude3Haiku="claude-3-haiku-20240307",d.Claude21="claude-2.1",d.ClaudeInstant12="claude-instant-1.2",d))(ht||{}),un=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(un||{});var ft=[{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var At=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,At(n)]))),e.items&&(e.items=At(e.items)),e},Ir=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...O()}),Ns=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...O()}),cn=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=e.modelConfig?.stream??this.config.stream,r;this.isVertex?r={name:o?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:r={name:"/messages"};let 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.filter(R=>R.role==="system").map(R=>({type:"text",text:R.content,...R.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(R=>R.role!=="system"),p=Gs(l),u=e.functions?.map(R=>({name:R.name,description:R.description,input_schema:R.parameters?At(R.parameters):void 0})),c=(this.config.tools??[]).map(R=>R&&typeof R=="object"&&"type"in R?R:{name:R.name,description:R.description,input_schema:R.input_schema?At(R.input_schema):void 0,...R.cache_control?{cache_control:R.cache_control}:{}}),m=[...u??[],...c];this.isVertex&&m.length>0&&(m=m.filter(R=>!(R&&typeof R=="object"&&"type"in R))),m.length===0&&(m=void 0);let g=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,x=e.modelConfig?.temperature,f=e.modelConfig?.topP,A=e.modelConfig?.topK??this.config.topK,I=e.modelConfig?.n??this.config.n;if(I&&I>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 R=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:R?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:R?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:R?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:R?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:R?.highest??32e3};break}}let y={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...g?{max_tokens:g}:{},...h&&h.length>0?{stop_sequences:h}:{},...x!==void 0&&!b?{temperature:x}:{},...f!==void 0&&(!b||f>=.95)?{top_p:f}:{},...A&&!b?{top_k:A}:{},...s,...m?{tools:m}:{},...o?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},messages:p};return[r,y]};createChatResp=e=>{if(e.type==="error")throw new E(e.error.message,void 0,void 0);let t=yr(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,o="",r="",s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(o+=u.text??"",Array.isArray(u.citations))for(let d of u.citations)d?.url&&a.push({url:String(d.url),title:typeof d.title=="string"?d.title:void 0,snippet:typeof d.cited_text=="string"?d.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(r+=u.thinking??"");break;case"tool_use":s.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};o&&(l.content=o),r&&(l.thought=r),s.length>0&&(l.functionCalls=s),a.length>0&&(l.citations=a);let p=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:p,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:r}=e;throw new E(r.message,void 0,void 0)}let o=0;if(e.type==="message_start"){let{message:r}=e,s=[{index:o,content:"",id:r.id}];return this.tokensUsed={promptTokens:r.usage?.input_tokens??0,completionTokens:r.usage?.output_tokens??0,totalTokens:(r.usage?.input_tokens??0)+(r.usage?.output_tokens??0)},{results:s}}if(e.type==="content_block_start"){let{content_block:r}=e;if(r.type==="text"){let s=[];if(Array.isArray(r.citations))for(let a of r.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:o,content:r.text,...s.length?{citations:s}:{}}]}}if(r.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="tool_use"&&typeof r.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=r.id;let s=[{id:r.id,type:"function",function:{name:r.name,params:""}}];return{results:[{index:o,functionCalls:s}]}}if(r.type==="web_search_tool_result"||r.type==="server_tool_use")return{results:[{index:o,content:""}]}}if(e.type==="content_block_delta"){let{delta:r}=e;if(r.type==="citations_delta"){let s=r.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:o,content:"",citations:a}]}}return{results:[{index:o,content:""}]}}if(r.type==="text_delta"){let s=[];if(Array.isArray(r.citations))for(let a of r.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:o,content:r.text,...s.length?{citations:s}:{}}]}}if(r.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="signature_delta")return{results:[{index:o,content:""}]};if(r.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:o,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:r.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:r,usage:s}=e;return this.tokensUsed={promptTokens:0,completionTokens:s.output_tokens,totalTokens:s.output_tokens},{results:[{index:o,content:"",finishReason:yr(r.stop_reason)}]}}return{results:[{index:o,content:""}]}}},we=class i extends D{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:o,options:r,models:s}){let a=t!==void 0&&n!==void 0,l,p;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,p=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",p=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let u={...Ir(),...o},d=new cn(u,a),c=m=>{let g=W({model:m,modelInfo:ft,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:g?.supported?.thinkingBudget??!1,multiTurn:!0}};super(d,{name:"Anthropic",apiURL:l,headers:p,modelInfo:ft,defaults:{model:u.model},options:r,supportFor:c,models:s})}};function Gs(i){let e=i.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(o=>{let r={};return typeof o.function.params=="string"?r=JSON.parse(o.function.params):typeof o.function.params=="object"&&(r=o.function.params),{type:"tool_use",id:o.id,name:o.function.name,input:r,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return $s(e)}function $s(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 o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function yr(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 xt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",y.O1="o1",y.O1Mini="o1-mini",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(xt||{}),Se=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Se||{});var ve=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1Pro="o1-pro",T.O1="o1",T.O1Mini="o1-mini",T.O3Pro="o3-pro",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(ve||{});var Oe=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],dn=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Us=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},ge=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...O()}),gn=()=>structuredClone({...ge(),model:"gpt-5"}),hn=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...N()}),fn=()=>({...ge(),model:"gpt-5-nano"}),mn=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq(e,t){let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o={name:"/chat/completions"},r=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Bs(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,p=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=Us(n),c={model:n,messages:a,...this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...r?{tools:r}:{},...s?{tool_choice:s}:{},...d?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...p&&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&&(c.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(c.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":c.reasoning_effort=void 0;break;case"minimal":c.reasoning_effort="minimal";break;case"low":c.reasoning_effort="medium";break;case"medium":c.reasoning_effort="high";break;case"high":c.reasoning_effort="high";break;case"highest":c.reasoning_effort="high";break}return this.chatReqUpdater&&(c=this.chatReqUpdater(c)),[o,c]}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}createChatResp(e){let{id:t,usage:n,choices:o,error:r}=e;if(r)throw r;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:o.map(a=>{if(a.message.refusal)throw new E(a.message.refusal,e.model,e.id);let l=br(a.finish_reason),p=a.message.tool_calls?.map(({id:u,function:{arguments:d,name:c}})=>({id:u,type:"function",function:{name:c,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:p,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:o,choices:r}=e;this.tokensUsed=o?{promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:r.map(({index:l,delta:{content:p,role:u,refusal:d,tool_calls:c,reasoning_content:m,annotations:g},finish_reason:h})=>{if(d)throw new E(d,void 0,n);let x=br(h),f=c?.map(({id:A,index:I,function:{name:b,arguments:y}})=>{typeof A=="string"&&typeof I=="number"&&!s.indexIdMap[I]&&(s.indexIdMap[I]=A);let R=s.indexIdMap[I];return R?{id:R,type:"function",function:{name:b,params:y}}:null}).filter(A=>A!==null);return{index:l,content:p??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:f,finishReason:x,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(o=>o.embedding)}}},br=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Bs(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(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.image}`,details:o.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:o.data,format:o.format==="wav"?"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(o=>({id:o.id,type:"function",function:{name:o.function.name,arguments:typeof o.function.params=="object"?JSON.stringify(o.function.params):o.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var _=class extends D{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new mn(t,n?.streamingUsage??!0,a);super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},Me=class extends _{constructor({apiKey:e,apiURL:t,config:n,options:o,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Oe,...s??[]];let a=l=>{let p=W({model:l,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:p?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,apiURL:t,config:{...ge(),...n},options:o,modelInfo:s,models:r,supportFor:a}),super.setName("OpenAI")}};var Tr=ge,qs=hn,zs=fn,js=gn,ke=class extends _{constructor({apiKey:e,resourceName:t,deploymentName:n,version:o="api-version=2024-02-15-preview",config:r,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 p={...Tr(),...r};l=[...Oe,...l??[]];let u=c=>{let m=W({model:c,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:p,options:s,models:a,modelInfo:l,supportFor:u});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${o}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var An=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.");Hs(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(),o=t.getMetrics();return n.latency.chat.mean-o.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,o=Date.now()-n,r=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return o>=r}handleFailure(){let t=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof j))throw n;switch(n.constructor){case se:throw n;case de:break;case oe:break;case re:break;case Z:break;case me:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Hs(i){let e=i.find(o=>o.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(o=>o.key));for(let o=0;o<i.length;o++){let r=i[o];if(!r)throw new Error(`Service at index ${o} is undefined`);let s=r.getModelList();if(!s)throw new Error(`Service at index ${o} (${r.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 ${o} (${r.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${o} (${r.getName()}) has extra model "${l}"`)}}function he(i){let e=!1,t=!1,n=!1,o=!1,r=!1,s=!1,a=!1,l=new Set,p=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let d of u.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),p+=85;break;case"audio":t=!0,d.cache&&(a=!0),p+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),p+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":o=!0,d.cache&&(a=!0),p+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),p+=Math.ceil(d.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(p+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(r=!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&&(o=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:o,requiresFunctions:r,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:p}}function Rr(i,e){let t=i.getFeatures(),n=[],o=[],r=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),r.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),r.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),r.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),r.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),r.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),r.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&o.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&&o.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:o,alternatives:r}}function xn(i,e){return i.map(t=>{let n=t.getFeatures(),o=Rr(t,e),r=0,s=[];return r+=10,e.hasImages&&n.media.images.supported&&(r+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(r+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(r+=3)),e.hasAudio&&n.media.audio.supported&&(r+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(r+=5)),e.hasFiles&&n.media.files.supported&&(r+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(r+=3)),e.hasUrls&&n.media.urls.supported&&(r+=25,s.push("URLs"),n.media.urls.webSearch&&(r+=5)),e.requiresFunctions&&n.functions&&(r+=15,s.push("Functions"),n.functionCot&&(r+=3)),e.requiresStreaming&&n.streaming&&(r+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(r+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(r+=3)),n.thinking&&(r+=2),n.multiTurn&&(r+=2),n.hasThinkingBudget&&(r+=1),n.hasShowThoughts&&(r+=1),r-=o.missingCapabilities.length*10,{provider:t,score:r,missingCapabilities:o.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function yn(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=he(i),o=xn(e,n);if(t.requireExactMatch){let r=o.filter(s=>s.missingCapabilities.length===0);if(r.length===0)throw new Error(`No providers fully support the request requirements: ${o[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return r[0].provider}if(!t.allowDegradation){let r=o[0];if(r.missingCapabilities.length>0)throw new Error(`Best available provider (${r.provider.getName()}) is missing: ${r.missingCapabilities.join(", ")}`)}return o[0].provider}function Ks(i,e){let t=he(i),n=xn(e,t),o=n[0]?.provider||null,r=[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=o?n[0].supportedCapabilities.length:0,a=o?`${o.getName()} supports ${s}/${r} requirements (${Math.round(s/Math.max(r,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:o,summary:a}}function Ws(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Vs(i,e){let t={};for(let n of i){let r=n.getFeatures().media[e];if(r.supported)for(let s of r.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var yt=(o=>(o.CommandRPlus="command-r-plus",o.CommandR="command-r",o.Command="command",o.CommandLight="command-light",o))(yt||{}),It=(o=>(o.EmbedEnglishV30="embed-english-v3.0",o.EmbedEnglishLightV30="embed-english-light-v3.0",o.EmbedMultiLingualV30="embed-multilingual-v3.0",o.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",o))(It||{});var In=[{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 wr=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...O()}),Js=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...N()}),bn=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),o=e.chatPrompt.slice(0,-1),r;n&&n.role==="user"&&typeof n.content=="string"&&(r=n?.content);let s=Qs(o),a=e.functions?.map(d=>{let c={};if(d.parameters?.properties)for(let[m,g]of Object.entries(d.parameters.properties))c[m]={description:g.description,type:g.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:c}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let c=a?.find(m=>m.name===d.functionId);if(!c)throw new Error("Function not found");return{call:{name:c.name,parameters:c.parameter_definitions},outputs:[{result:d.result??""}]}}),p={name:"/chat"},u={message:r,model:t,tools:a,...l&&!r?{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[p,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"},o={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,o]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(r=>({id:r.name,type:"function",function:{name:r.name,params:r.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:o}=this.createChatResp(e),r=o[0];if(!r)throw new Error("No result");return r.id=n.generation_id??"",{results:o}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Ee=class extends D{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("Cohere API key not set");let r={...wr(),...t},s=new bn(r);super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:In,defaults:{model:r.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:o})}};function Qs(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=Cr(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),o=Cr(n)?.at(0);if(!o)throw new Error("Function call not found");let r=[{result:e.result}];return{role:"TOOL",tool_results:[{call:o,outputs:r}]}}default:throw new Error("Unknown role")}})}function Cr(i){return i?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var bt=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(bt||{});var Tn=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Sr=()=>structuredClone({model:"deepseek-chat",...O()}),Ys=()=>structuredClone({model:"deepseek-coder",...N()}),Pe=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...Sr(),...t};r=[...Tn,...r??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:r,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:o}),super.setName("DeepSeek")}};var Tt=(u=>(u.Gemini25Pro="gemini-2.5-pro",u.Gemini25Flash="gemini-2.5-flash",u.Gemini25FlashLite="gemini-2.5-flash-lite",u.Gemini20Flash="gemini-2.0-flash",u.Gemini20FlashLite="gemini-2.0-flash-lite",u.Gemini1Pro="gemini-1.0-pro",u.Gemini15Flash="gemini-1.5-flash",u.Gemini15Flash002="gemini-1.5-flash-002",u.Gemini15Flash8B="gemini-1.5-flash-8b",u.Gemini15Pro="gemini-1.5-pro",u))(Tt||{}),Rn=(o=>(o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(Rn||{}),Cn=(o=>(o.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",o.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",o.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",o.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",o))(Cn||{}),wn=(r=>(r.BlockNone="BLOCK_NONE",r.BlockOnlyHigh="BLOCK_ONLY_HIGH",r.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",r.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",r.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",r))(wn||{}),vr=(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))(vr||{});var Sn=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var vn=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,vn(n)]))),e.items&&(e.items=vn(e.items)),e},Or=[{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"}],Mr=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Or,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...O()}),Xs=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Or,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...N()}),On=class{constructor(e,t,n,o,r){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=o;this.options=r;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,o=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r;if(this.endpointId?r={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:r={name:o?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=o?"&":"?",x=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;r.name+=`${h}key=${x}`}let s=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(h=>h.role!=="system").map((h,x)=>{switch(h.role){case"user":return{role:"user",parts:Array.isArray(h.content)?h.content.map((A,I)=>{switch(A.type){case"text":return{text:A.text};case"image":return{inlineData:{mimeType:A.mimeType,data:A.image}};case"audio":return{inlineData:{mimeType:`audio/${A.format??"mp3"}`,data:A.data}};case"file":return"fileUri"in A?{fileData:{mimeType:A.mimeType,fileUri:A.fileUri}}:{inlineData:{mimeType:A.mimeType,data:A.data}};default:throw new Error(`Chat prompt content type not supported (index: ${I})`)}}):[{text:h.content}]};case"assistant":{let f=[];if(h.functionCalls){if(f=h.functionCalls.map(A=>{let I=typeof A.function.params=="string"?JSON.parse(A.function.params):A.function.params;return{functionCall:{name:A.function.name,args:I}}}),!f)throw new Error("Function call is empty");return{role:"model",parts:f}}if(!h.content)throw new Error("Assistant content is empty");return f=[{text:h.content}],{role:"model",parts:f}}case"function":{if(!("functionId"in h))throw new Error(`Chat prompt functionId is empty (index: ${x})`);return{role:"user",parts:[{functionResponse:{name:h.functionId,response:{result:h.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(h)} (index: ${x})`)}}),p=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(x=>({...x,parameters:x.parameters?vn(x.parameters):void 0}));p.push({function_declarations:h})}this.options?.codeExecution&&p.push({code_execution:{}}),this.options?.googleSearchRetrieval&&p.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&p.push({google_search:{}}),this.options?.urlContext&&p.push({url_context:{}}),p.length===0&&(p=void 0);let u;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...h}}else p&&p.length>0&&(u={function_calling_config:{mode:"AUTO"}});let d={};if(this.config.thinking?.includeThoughts&&(d.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let h=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=h?.minimal??200;break;case"low":d.thinkingBudget=h?.low??800;break;case"medium":d.thinkingBudget=h?.medium??5e3;break;case"high":d.thinkingBudget=h?.high??1e4;break;case"highest":d.thinkingBudget=h?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(d.includeThoughts=t.showThoughts);let 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",...Object.keys(d).length>0?{thinkingConfig:d}:{}},m=this.config.safetySettings;return[r,{contents:l,tools:p,toolConfig:u,systemInstruction:a,generationConfig:c,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,o;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},o={instances:e.texts.map(r=>({content:r,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let r=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${r}`},o={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,o]};createChatResp=e=>{let t=e.candidates?.map(n=>{let o={index:0};switch(n.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new E("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new E("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new E("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new E("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new E("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new E("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new E("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new E("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new E("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return o;for(let s of n.content.parts){if("text"in s){"thought"in s&&s.thought?o.thought=s.text:o.content=s.text;continue}"functionCall"in s&&(o.functionCalls=[{id:B(),type:"function",function:{name:s.functionCall.name,params:s.functionCall.args}}])}let r=n.citationMetadata?.citations;if(Array.isArray(r)&&r.length){let s=a=>a?`${a.year}-${String(a.month).padStart(2,"0")}-${String(a.day).padStart(2,"0")}`:void 0;o.citations=r.filter(a=>typeof a?.uri=="string").map(a=>({url:a.uri,title:a.title,license:a.license,publicationDate:s(a.publicationDate)}))}return o});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Fe=class i extends D{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:o,config:r,options:s,models:a,modelInfo:l}){let p=t!==void 0&&n!==void 0,u,d;if(p){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;o?h="endpoints":h="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let c={...Mr(),...r},m=new On(c,p,o,e,s);l=[...Sn,...l??[]];let g=h=>{let x=W({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}};super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:c.model,embedModel:c.embedModel},options:s,supportFor:g,models:a})}};var Zs=new $,_e=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(Zs.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 Rt=(o=>(o.Llama3_8B="llama3-8b-8192",o.Llama33_70B="llama-3.3-70b-versatile",o.Mixtral_8x7B="mixtral-8x7b-32768",o.Gemma2_9B="gemma2-9b-it",o))(Rt||{});var Mn=[{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 ei=()=>structuredClone({model:"llama-3.3-70b-versatile",...O()}),De=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Groq API key not set");let s={...ei(),...t},a={...n,streamingUsage:!1};r=[...Mn,...r??[]];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:r,apiURL:"https://api.groq.com/openai/v1",models:o,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new _e(t,t/60,{debug:e?.debug});return async(r,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await r()}}};var kn=[];var En=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(En||{});var kr=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...O()}),ti=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...N()}),Pn=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:
146
146
  ${JSON.stringify(e.functions,null,2)}
147
- `:"",o=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let p=l.functionCalls?.map(u=>{let c=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${c})`}).join(`
147
+ `:"",o=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let p=l.functionCalls?.map(u=>{let d=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${d})`}).join(`
148
148
  `);return p?`Assistant: ${l.content}
149
149
  Functions:
150
150
  ${p}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
151
- `),r=`${n} ${o}`.trim(),s={name:"/models"},a={model:t,inputs:r,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[s,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Le=class extends _{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("HuggingFace API key not set");let r={...kr(),...t},s=new Pn(r);super(s,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:kn,defaults:{model:r.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:o})}};var Ct=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Ct||{}),Er=(e=>(e.MistralEmbed="mistral-embed",e))(Er||{});var Fn=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var _n=()=>structuredClone({model:"mistral-small-latest",...O(),topP:1}),oi=()=>structuredClone({..._n(),model:"mistral-large-latest"}),Ne=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Mistral API key not set");let s={..._n(),...t};r=[...Fn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=p=>{let{max_completion_tokens:u,messages:c,...d}=p;return{...d,messages:this.updateMessages(c),max_tokens:u}};super({apiKey:e,config:s,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let o=n.content.map(r=>typeof r=="object"&&r!==null&&"image_url"in r?{type:"image_url",image_url:{url:r.image_url?.url}}:r);t.push({...n,content:o})}else t.push(n);return t}};var Dn=class{constructor(e={}){this.config=e;this.config.id=this.config.id??q()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((o,r)=>o+r,0)/n.length,n.length>0){let o=[...n].sort((a,l)=>a-l),r=Math.max(0,Math.floor(o.length*.95)-1);this.metrics.latency[e].p95=o[r]??t;let s=Math.max(0,Math.floor(o.length*.99)-1);this.metrics.latency[e].p99=o[s]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let o=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=o>0?this.metrics.errors[e].count/o:0}}};var Ln=class i{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:r,description:s,isInternal:a}=n;this.services.set(n.key,{service:r,description:s,isInternal:a})}else{let r=n.getModelList();if(!r)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let s of r){if(this.services.has(s.key)){let a=this.services.get(s.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${s.key} as service ${a?.getName()}`)}if("model"in s&&typeof s.model)this.services.set(s.key,{description:s.description,service:n,model:s.model});else if("embedModel"in s&&s.embedModel)this.services.set(s.key,{description:s.description,service:n,embedModel:s.embedModel});else throw new Error(`Key ${s.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new i(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{model:r,...s}=e;return await o.service.chat(s,t)}return await o.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{embedModel:r,...s}=e;return await o.service.embed(s,t)}return await o.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Pr=()=>structuredClone({...O(),model:"nous-hermes2",embedModel:"all-minilm"}),ri=()=>structuredClone({...L(),model:"nous-hermes2",embedModel:"all-minilm"}),$e=class extends F{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:o,models:r}){let s={...Pr(),...n};super({apiKey:e,options:o,config:s,apiURL:t,models:r,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var si=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),Ge=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let o of e){if(o.type==="text"){t==="assistant"?n.push({type:"output_text",text:o.text}):n.push({type:"input_text",text:o.text});continue}if(t==="assistant")continue;if(o.type==="image"){let s=`data:${o.mimeType};base64,${o.image}`;n.push({type:"input_image",image_url:{url:s,details:o.details??"auto"}});continue}if(o.type==="audio"){n.push({type:"input_audio",input_audio:{data:o.data,format:o.format==="wav"?"wav":void 0}});continue}let r=o;throw new Error(`Unsupported content part: ${JSON.stringify(r)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let o of e){if(t&&o.role==="system")continue;let r;if(o.role==="system"||o.role==="user"||o.role==="assistant"&&o.content)if(typeof o.content=="string")o.role==="system"?r=o.content:o.role==="assistant"?r=[{type:"output_text",text:o.content}]:r=[{type:"input_text",text:o.content}];else if(Array.isArray(o.content))r=this.mapInternalContentToResponsesInput(o.content,o.role==="assistant"?"assistant":"user");else{if(!(o.role==="assistant"&&!o.content&&o.functionCalls))throw new Error(`Invalid content type for role ${o.role}`);r=""}else o.role,r="";switch(o.role){case"system":n.push({type:"message",role:"system",content:r});break;case"user":n.push({type:"message",role:"user",content:r,name:o.name});break;case"assistant":if(o.content||o.functionCalls){let s={type:"message",role:"assistant",content:""};if(o.content&&(s.content=r),o.name&&(s.name=o.name),o.content&&n.push(s),o.functionCalls)for(let a of o.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:o.functionId,output:o.result});break;default:{let s=o.role;throw new Error(`Invalid role in chat prompt: ${s}`)}}}return n}createChatReq(e,t){let n=e.model,o={name:"/responses"},r=null,s=!1;if(e.chatPrompt){for(let I of e.chatPrompt)if(I.role==="system"&&typeof I.content=="string"){r=I.content,s=!0;break}}let a=r??this.config.systemPrompt??null,l=e.functions?.map(I=>({type:"function",name:I.name,description:I.description,parameters:I.parameters??{}})),p=[],u=si(n),c=this.config.reasoningSummary;t?.showThoughts?c||(c="auto"):c=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...u?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:p.length>0?p:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:c}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,s):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"minimal"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[o,f]}createChatResp(e){let{id:t,output:n,usage:o}=e;o&&(this.tokensUsed={promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens??o.output_tokens??0,totalTokens:o.total_tokens});let r={};for(let s of n??[])switch(s.type){case"message":r.id=s.id,r.content=Nn(s.content,t),r.finishReason=s.status==="completed"?"stop":"content_filter",r.citations=wt(s.content);break;case"reasoning":r.id=s.id,s.encrypted_content?r.thought=s.encrypted_content:r.thought=s.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
151
+ `),r=`${n} ${o}`.trim(),s={name:"/models"},a={model:t,inputs:r,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[s,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Le=class extends D{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("HuggingFace API key not set");let r={...kr(),...t},s=new Pn(r);super(s,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:kn,defaults:{model:r.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:o})}};var Ct=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Ct||{}),Er=(e=>(e.MistralEmbed="mistral-embed",e))(Er||{});var Fn=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var _n=()=>structuredClone({model:"mistral-small-latest",...O(),topP:1}),ni=()=>structuredClone({..._n(),model:"mistral-large-latest"}),Ne=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Mistral API key not set");let s={..._n(),...t};r=[...Fn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=p=>{let{max_completion_tokens:u,messages:d,...c}=p;return{...c,messages:this.updateMessages(d),max_tokens:u}};super({apiKey:e,config:s,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let o=n.content.map(r=>typeof r=="object"&&r!==null&&"image_url"in r?{type:"image_url",image_url:{url:r.image_url?.url}}:r);t.push({...n,content:o})}else t.push(n);return t}};var Dn=class{constructor(e={}){this.config=e;this.config.id=this.config.id??B()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((o,r)=>o+r,0)/n.length,n.length>0){let o=[...n].sort((a,l)=>a-l),r=Math.max(0,Math.floor(o.length*.95)-1);this.metrics.latency[e].p95=o[r]??t;let s=Math.max(0,Math.floor(o.length*.99)-1);this.metrics.latency[e].p99=o[s]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let o=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=o>0?this.metrics.errors[e].count/o:0}}};var Ln=class i{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:r,description:s,isInternal:a}=n;this.services.set(n.key,{service:r,description:s,isInternal:a})}else{let r=n.getModelList();if(!r)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let s of r){if(this.services.has(s.key)){let a=this.services.get(s.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${s.key} as service ${a?.getName()}`)}if("model"in s&&typeof s.model)this.services.set(s.key,{description:s.description,service:n,model:s.model});else if("embedModel"in s&&s.embedModel)this.services.set(s.key,{description:s.description,service:n,embedModel:s.embedModel});else throw new Error(`Key ${s.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new i(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{model:r,...s}=e;return await o.service.chat(s,t)}return await o.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{embedModel:r,...s}=e;return await o.service.embed(s,t)}return await o.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Pr=()=>structuredClone({...O(),model:"nous-hermes2",embedModel:"all-minilm"}),oi=()=>structuredClone({...N(),model:"nous-hermes2",embedModel:"all-minilm"}),Ge=class extends _{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:o,models:r}){let s={...Pr(),...n};super({apiKey:e,options:o,config:s,apiURL:t,models:r,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var ri=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),$e=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let o of e){if(o.type==="text"){t==="assistant"?n.push({type:"output_text",text:o.text}):n.push({type:"input_text",text:o.text});continue}if(t==="assistant")continue;if(o.type==="image"){let s=`data:${o.mimeType};base64,${o.image}`;n.push({type:"input_image",image_url:{url:s,details:o.details??"auto"}});continue}if(o.type==="audio"){n.push({type:"input_audio",input_audio:{data:o.data,format:o.format==="wav"?"wav":void 0}});continue}let r=o;throw new Error(`Unsupported content part: ${JSON.stringify(r)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let o of e){if(t&&o.role==="system")continue;let r;if(o.role==="system"||o.role==="user"||o.role==="assistant"&&o.content)if(typeof o.content=="string")o.role==="system"?r=o.content:o.role==="assistant"?r=[{type:"output_text",text:o.content}]:r=[{type:"input_text",text:o.content}];else if(Array.isArray(o.content))r=this.mapInternalContentToResponsesInput(o.content,o.role==="assistant"?"assistant":"user");else{if(!(o.role==="assistant"&&!o.content&&o.functionCalls))throw new Error(`Invalid content type for role ${o.role}`);r=""}else o.role,r="";switch(o.role){case"system":n.push({type:"message",role:"system",content:r});break;case"user":n.push({type:"message",role:"user",content:r,name:o.name});break;case"assistant":if(o.content||o.functionCalls){let s={type:"message",role:"assistant",content:""};if(o.content&&(s.content=r),o.name&&(s.name=o.name),o.content&&n.push(s),o.functionCalls)for(let a of o.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:o.functionId,output:o.result});break;default:{let s=o.role;throw new Error(`Invalid role in chat prompt: ${s}`)}}}return n}createChatReq(e,t){let n=e.model,o={name:"/responses"},r=null,s=!1;if(e.chatPrompt){for(let f of e.chatPrompt)if(f.role==="system"&&typeof f.content=="string"){r=f.content,s=!0;break}}let a=r??this.config.systemPrompt??null,l=e.functions?.map(f=>({type:"function",name:f.name,description:f.description,parameters:f.parameters??{}})),p=[],u=ri(n),d=this.config.reasoningSummary;t?.showThoughts?d||(d="auto"):d=void 0;let c=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":c=void 0;break;case"minimal":c="minimal";break;case"low":c="medium";break;case"medium":case"high":case"highest":c="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...u?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:p.length>0?p:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...c?{reasoning:{effort:c,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,s):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"minimal"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let x=m;return this.responsesReqUpdater&&(x=this.responsesReqUpdater(x)),[o,x]}createChatResp(e){let{id:t,output:n,usage:o}=e;o&&(this.tokensUsed={promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens??o.output_tokens??0,totalTokens:o.total_tokens});let r={};for(let s of n??[])switch(s.type){case"message":r.id=s.id,r.content=Nn(s.content,t),r.finishReason=s.status==="completed"?"stop":"content_filter",r.citations=wt(s.content);break;case"reasoning":r.id=s.id,s.encrypted_content?r.thought=s.encrypted_content:r.thought=s.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
152
152
  `);break;case"file_search_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries,results:s.results}}}],r.finishReason="function_call";break;case"web_search_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries}}}],r.finishReason="function_call";break;case"computer_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action}}}],r.finishReason="function_call";break;case"code_interpreter_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code,results:s.results}}}],r.finishReason="function_call";break;case"image_generation_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}],r.finishReason="function_call";break;case"local_shell_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action}}}],r.finishReason="function_call";break;case"mcp_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name,args:s.args,serverLabel:s.server_label,output:s.output,error:s.error}}}],r.finishReason="function_call";break;case"function_call":r.id=s.id,r.functionCalls=[{id:s.id,type:"function",function:{name:s.name,params:s.arguments}}],r.finishReason="function_call";break}return{results:[{...r,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},o;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":o=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=Nn(t.item.content,t.item.id),n.citations=wt(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"file_search",params:{queries:r.queries||[],results:r.results?.map(s=>({fileId:s.file_id,filename:s.filename,score:s.score,text:s.text,attributes:s.attributes}))}}}]}break;case"web_search_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"web_search",params:{queries:r.queries||[]}}}]}break;case"computer_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"computer_use",params:{action:r.action||{}}}}]}break;case"code_interpreter_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"code_interpreter",params:{code:r.code||"",results:r.results}}}]}break;case"image_generation_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"image_generation",params:{result:r.result}}}]}break;case"local_shell_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"local_shell",params:{action:r.action||{}}}}]}break;case"mcp_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"mcp",params:{name:r.name||"",args:r.args||"",serverLabel:r.server_label||"",output:r.output,error:r.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Nn([t.part],t.item_id),n.citations=wt([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let r=wt(t.item.content||[]);r&&(n.citations=r)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),o=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":o=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":o=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:o}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}},Nn=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(o=>o.refusal).join(`
153
153
  `);throw new E(n,void 0,e)}return i.filter(n=>n.type==="output_text").map(n=>n.text).join(`
154
- `)};function wt(i){let e=[];for(let t of i??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var vt=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),ii=()=>({...vt(),model:"gpt-4o",temperature:.5}),ai=()=>({...vt(),model:"gpt-4o",temperature:.9}),St=class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=[],models:s,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new Ge(t,n?.streamingUsage??!0,a),u=s;super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:u})}},Ue=class extends St{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...dn,...r??[]];let s=a=>{let l=W({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...vt(),...t},options:n,modelInfo:r,models:o,supportFor:s})}};var Fr=()=>structuredClone({model:"openrouter/auto",...O()}),Be=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r,referer:s,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Fr(),...t},p={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},u=r??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:o,supportFor:p}),super.setName("OpenRouter"),super.setHeaders(async()=>{let c={Authorization:`Bearer ${e}`};return s&&(c["HTTP-Referer"]=s),a&&(c["X-Title"]=a),c})}};async function $n(i,e,t={}){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return[{type:"text",text:String(i)}];let n=e.getFeatures(),o=[];for(let r of i)try{switch(r.type){case"text":o.push({type:"text",text:r.text});break;case"image":if(n.media.images.supported)r.altText?o.push({type:"text",text:`[Image: ${r.altText}]`}):o.push({type:"text",text:"[Image content]"});else if(r.altText)o.push({type:"text",text:r.altText});else if(t.imageToText)try{let s=await t.imageToText(r.image);o.push({type:"text",text:s})}catch(s){throw new ee(s,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new V("Images",e.getName(),!1);case"skip":continue;default:o.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)r.transcription?o.push({type:"text",text:r.transcription}):o.push({type:"text",text:"[Audio content]"});else if(r.transcription)o.push({type:"text",text:r.transcription});else if(t.audioToText)try{let s=await t.audioToText(r.data,r.format);o.push({type:"text",text:s})}catch(s){throw new ee(s,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new V("Audio",e.getName(),!1);case"skip":continue;case"degrade":o.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)r.extractedText?o.push({type:"text",text:r.extractedText}):o.push({type:"text",text:`[File: ${r.filename}]`});else if(r.extractedText)o.push({type:"text",text:r.extractedText});else if(t.fileToText)try{let s=await t.fileToText(r.data,r.mimeType);o.push({type:"text",text:s})}catch(s){throw new ee(s,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new V("Files",e.getName(),!1);case"skip":continue;default:o.push({type:"text",text:`[File: ${r.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)r.cachedContent?o.push({type:"text",text:r.cachedContent}):o.push({type:"text",text:`[Link: ${r.url}${r.title?` - ${r.title}`:""}]`});else if(r.cachedContent)o.push({type:"text",text:r.cachedContent});else if(t.urlToText)try{let s=await t.urlToText(r.url);o.push({type:"text",text:s})}catch(s){throw new ee(s,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new V("URLs",e.getName(),!1);case"skip":continue;case"degrade":o.push({type:"text",text:`[Link: ${r.url}${r.title?` - ${r.title}`:""}]`})}break;default:typeof r=="object"&&r.text?o.push({type:"text",text:r.text}):o.push({type:"text",text:String(r)})}}catch(s){throw s instanceof V||s instanceof ee?s:new ee(s,r.type||"unknown","content processing")}return o}function li(i){let e=!1,t=!1,n=!1,o=!1;for(let r of i)if(r.role==="user"&&Array.isArray(r.content))for(let s of r.content)switch(s.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":o=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:o}}var Ot=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Ot||{});var Gn=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var Mt=()=>structuredClone({model:"reka-core",...O()}),pi=()=>structuredClone({...Mt(),model:"reka-core"}),ui=()=>structuredClone({model:"reka-core",...L()}),ci=()=>({...Mt(),model:"reka-flash"}),Un=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},o=di(e),r=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,s=e.modelConfig?.stream??this.config.stream,a={model:t,messages:o,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...r?{frequency_penalty:r}:{},...s?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((s,a)=>{let l=_r(s.finish_reason),p;return typeof s.message.content=="string"?p=s.message.content:p=s.message.content.text,{index:a,id:`${t}`,content:p,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((s,a)=>{let l=_r(s.finish_reason),p;return typeof s.chunk.content=="string"?p=s.chunk.content:p=s.chunk.content.text,{index:a,id:`${t}`,content:p,finishReason:l}})}}},_r=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function di(i){return i.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var qe=class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=Gn,models:s}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Mt(),...t},l=new Un(a);super(l,{name:"Reka",apiURL:o||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:r,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,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:s})}};var Bn=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),o=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(o,t),routing:n}}catch(r){if(r instanceof V&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw r}}async preprocessRequest(e,t,n){let o={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},r=[];for(let s of e.chatPrompt)if(s.role==="user"&&Array.isArray(s.content)){let a=await $n(s.content,t,o);a.every(p=>p.type==="text")&&a.length===1?r.push({...s,content:a[0].text}):r.push({...s,content:a.map(p=>({type:"text",text:p.text}))})}else r.push(s);return{...e,chatPrompt:r}}async selectProviderWithDegradation(e,t){let n=he(e),o=[],r=[],s=[];try{let a=yn(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(r.push("Images will be converted to text descriptions"),o.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(r.push("Audio will be transcribed to text"),o.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(r.push("File content will be extracted to text"),o.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(r.push("URL content will be pre-fetched"),o.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&s.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&s.push("Content caching not supported"),{provider:a,processingApplied:o,degradations:r,warnings:s}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let o of t)try{let r={provider:o,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},s=await this.preprocessRequest(e,o,{fallbackBehavior:"degrade"});return{response:await o.chat(s,n),routing:r}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=he(e),n=[],o=[];try{let r=await this.selectProviderWithDegradation(e,{});return r.degradations.length>0&&(n.push(...r.degradations),o.push("Consider using a provider that natively supports all media types")),r.warnings.length>0&&n.push(...r.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),o.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),o.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||r.degradations.length>0,issues:n,recommendations:o}}catch(r){return{canHandle:!1,issues:[`Cannot route request: ${r instanceof Error?r.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),o=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(o)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(o)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(o)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(o)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(o)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(o)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(o))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var qn=[];var Dr=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...O()}),ze=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Together API key not set");let s={...Dr(),...t};r=[...qn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:r,models:o,supportFor:a}),super.setName("Together")}};var kt=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(kt||{});var zn=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var Lr=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...O()}),mi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...L()}),jn=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(u=>u.type==="text").map(u=>u.text).join(`
155
- `));let p={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...p,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:p}),o=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),r={name:"/chat/completions",localCall:async(a,l)=>{try{let p=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(u){try{for await(let c of p)u.enqueue(c);u.close()}catch(c){u.error(c)}}}):p}catch(p){throw new Error(`WebLLM API error: ${p}`)}}},s={model:t,messages:n,...o?.length?{tools:o}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[r,s]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,o)=>{let r="stop";switch(n.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let s=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:o,id:e.id,content:n.message.content||"",functionCalls:s,finishReason:r}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,o=e.choices[0];if(!o)throw new Error("No choice in WebLLM stream response");if(o.delta.content&&(n.content=(n.content||"")+o.delta.content),o.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of o.delta.tool_calls){let p=n.toolCalls[l.index];p?l.function?.arguments&&(p.function.arguments=(p.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let r;if(o.finish_reason)switch(o.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let s=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:s,finishReason:r}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},je=class extends _{constructor({engine:e,config:t,options:n,models:o}){if(!e)throw new Error("WebLLM engine instance is required");let r={...Lr(),...t},s=new jn(r,e);super(s,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:zn,defaults:{model:r.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:o})}};var Et=(o=>(o.Grok3="grok-3",o.Grok3Mini="grok-3-mini",o.Grok3Fast="grok-3-fast",o.Grok3MiniFast="grok-3-mini-fast",o))(Et||{}),Nr=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Nr||{});var Hn=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var Kn=()=>structuredClone({model:"grok-3-mini",...O()}),gi=()=>structuredClone({...Kn(),model:"grok-3"}),He=class extends F{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Grok API key not set");let s={...Kn(),...t};r=[...Hn,...r??[]];let a=p=>{let u=W({model:p,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=p=>{if(n?.searchParameters){let u=n.searchParameters;return{...p,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(c=>({type:c.type,country:c.country,excluded_websites:c.excludedWebsites,allowed_websites:c.allowedWebsites,safe_search:c.safeSearch,x_handles:c.xHandles,links:c.links}))}}}return p};super({apiKey:e,config:s,options:n,apiURL:"https://api.x.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function hi(i){return Pt.create(i)}var Pt=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new Me(e);break;case"openai-responses":this.ai=new Ue(e);break;case"azure-openai":this.ai=new ke(e);break;case"grok":this.ai=new He(e);break;case"huggingface":this.ai=new Le(e);break;case"groq":this.ai=new De(e);break;case"together":this.ai=new ze(e);break;case"openrouter":this.ai=new Be(e);break;case"cohere":this.ai=new Ee(e);break;case"google-gemini":this.ai=new Fe(e);break;case"anthropic":this.ai=new we(e);break;case"mistral":this.ai=new Ne(e);break;case"deepseek":this.ai=new Pe(e);break;case"ollama":this.ai=new $e(e);break;case"reka":this.ai=new qe(e);break;case"webllm":this.ai=new je(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};import{SpanKind as Wn}from"@opentelemetry/api";var Q=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Wn.SERVER,attributes:{[S.DB_SYSTEM]:this.name,[S.DB_OPERATION_NAME]:"upsert",[S.DB_TABLE]:e.table,[S.DB_NAMESPACE]:e.namespace,[S.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Wn.SERVER,attributes:{[S.DB_SYSTEM]:this.name,[S.DB_OPERATION_NAME]:"upsert",[S.DB_TABLE]:e[0].table,[S.DB_NAMESPACE]:e[0].namespace,[S.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Wn.SERVER,attributes:{[S.DB_SYSTEM]:this.name,[S.DB_OPERATION_NAME]:"upsert",[S.DB_TABLE]:e.table,[S.DB_NAMESPACE]:e.namespace,[S.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Vn="https://api.cloudflare.com/client/v4/accounts/",Ke=class extends Q{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:o}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:o}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let o=await z({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(o.errors)throw new Error(`Cloudflare upsert failed: ${o.errors.map(({message:r})=>r).join(", ")}`);return{ids:o.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let o=e[0].table,r=await z({url:new URL(`${this.accountId}/vectorize/indexes/${o}/upsert`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(s=>({id:s.id,values:s.values,namespace:s.namespace,metadata:s.metadata})));if(r.errors)throw new Error(`Cloudflare batch upsert failed: ${r.errors.map(({message:s})=>s).join(", ")}`);return{ids:r.result.ids}};query=async(e,t)=>{let n=await z({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:r})=>r).join(", ")}`);return{matches:n.result.matches.map(({id:r,score:s,values:a,metadata:l})=>({id:r,score:s,values:a,metadata:l}))}}};var ie=class extends Q{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let o=this.state[e.table];if(!o)throw new Error(`Table not found: ${e.table}`);o[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let o=[];for(let r of e){let s=await this.upsert(r,t);o.push(...s.ids)}return{ids:o}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let o=[];return Object.entries(n).forEach(([r,s])=>{if(e.values&&s.values){let a=fi(e.values,s.values);o.push({id:r,score:a,metadata:s.metadata})}}),o.sort((r,s)=>r.score-s.score),e.limit&&(o.length=e.limit),{matches:o}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},fi=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,o=0,r=!0,s=!0,a=new Float64Array(i),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],o+=l[d]*l[d],a[d]!==0&&(r=!1),l[d]!==0&&(s=!1);if(r||s)return 1;let p=Math.sqrt(n),u=Math.sqrt(o);return 1-t/(p*u)};var Ai=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),We=class extends Q{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await z({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:o,values:r=[],metadata:s})=>({id:o,values:r,metadata:s}))),{ids:e.map(({id:o})=>o)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await z({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},Ai(e))).matches.map(({id:r,score:s,values:a,metadata:l})=>({id:r,score:s,metadata:l,values:a}))}}};var Ve=class extends Q{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let o=await z({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(o?.result?.errors)throw new Error(`Weaviate upsert failed: ${o.result.errors.error.map(({message:r})=>r).join(", ")}`);return{ids:[o.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let o=e.map(s=>({id:s.id,class:s.table,tenant:s.namespace,vector:s.values,properties:s.metadata??{}})),r=await z({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:o});if(r?.some(({result:s})=>s?.errors))throw new Error(`Weaviate batch upsert failed: ${r.map(({result:s})=>s?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:r.map(({id:s})=>s)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
154
+ `)};function wt(i){let e=[];for(let t of i??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var vt=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),si=()=>({...vt(),model:"gpt-4o",temperature:.5}),ii=()=>({...vt(),model:"gpt-4o",temperature:.9}),St=class extends D{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=[],models:s,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new $e(t,n?.streamingUsage??!0,a),u=s;super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:u})}},Ue=class extends St{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...dn,...r??[]];let s=a=>{let l=W({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...vt(),...t},options:n,modelInfo:r,models:o,supportFor:s})}};var Fr=()=>structuredClone({model:"openrouter/auto",...O()}),Be=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r,referer:s,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Fr(),...t},p={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},u=r??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:o,supportFor:p}),super.setName("OpenRouter"),super.setHeaders(async()=>{let d={Authorization:`Bearer ${e}`};return s&&(d["HTTP-Referer"]=s),a&&(d["X-Title"]=a),d})}};async function Gn(i,e,t={}){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return[{type:"text",text:String(i)}];let n=e.getFeatures(),o=[];for(let r of i)try{switch(r.type){case"text":o.push({type:"text",text:r.text});break;case"image":if(n.media.images.supported)r.altText?o.push({type:"text",text:`[Image: ${r.altText}]`}):o.push({type:"text",text:"[Image content]"});else if(r.altText)o.push({type:"text",text:r.altText});else if(t.imageToText)try{let s=await t.imageToText(r.image);o.push({type:"text",text:s})}catch(s){throw new ee(s,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new V("Images",e.getName(),!1);case"skip":continue;default:o.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)r.transcription?o.push({type:"text",text:r.transcription}):o.push({type:"text",text:"[Audio content]"});else if(r.transcription)o.push({type:"text",text:r.transcription});else if(t.audioToText)try{let s=await t.audioToText(r.data,r.format);o.push({type:"text",text:s})}catch(s){throw new ee(s,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new V("Audio",e.getName(),!1);case"skip":continue;case"degrade":o.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)r.extractedText?o.push({type:"text",text:r.extractedText}):o.push({type:"text",text:`[File: ${r.filename}]`});else if(r.extractedText)o.push({type:"text",text:r.extractedText});else if(t.fileToText)try{let s=await t.fileToText(r.data,r.mimeType);o.push({type:"text",text:s})}catch(s){throw new ee(s,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new V("Files",e.getName(),!1);case"skip":continue;default:o.push({type:"text",text:`[File: ${r.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)r.cachedContent?o.push({type:"text",text:r.cachedContent}):o.push({type:"text",text:`[Link: ${r.url}${r.title?` - ${r.title}`:""}]`});else if(r.cachedContent)o.push({type:"text",text:r.cachedContent});else if(t.urlToText)try{let s=await t.urlToText(r.url);o.push({type:"text",text:s})}catch(s){throw new ee(s,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new V("URLs",e.getName(),!1);case"skip":continue;case"degrade":o.push({type:"text",text:`[Link: ${r.url}${r.title?` - ${r.title}`:""}]`})}break;default:typeof r=="object"&&r.text?o.push({type:"text",text:r.text}):o.push({type:"text",text:String(r)})}}catch(s){throw s instanceof V||s instanceof ee?s:new ee(s,r.type||"unknown","content processing")}return o}function ai(i){let e=!1,t=!1,n=!1,o=!1;for(let r of i)if(r.role==="user"&&Array.isArray(r.content))for(let s of r.content)switch(s.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":o=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:o}}var Ot=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Ot||{});var $n=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var Mt=()=>structuredClone({model:"reka-core",...O()}),li=()=>structuredClone({...Mt(),model:"reka-core"}),pi=()=>structuredClone({model:"reka-core",...N()}),ui=()=>({...Mt(),model:"reka-flash"}),Un=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},o=ci(e),r=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,s=e.modelConfig?.stream??this.config.stream,a={model:t,messages:o,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...r?{frequency_penalty:r}:{},...s?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((s,a)=>{let l=_r(s.finish_reason),p;return typeof s.message.content=="string"?p=s.message.content:p=s.message.content.text,{index:a,id:`${t}`,content:p,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((s,a)=>{let l=_r(s.finish_reason),p;return typeof s.chunk.content=="string"?p=s.chunk.content:p=s.chunk.content.text,{index:a,id:`${t}`,content:p,finishReason:l}})}}},_r=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function ci(i){return i.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var qe=class extends D{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=$n,models:s}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Mt(),...t},l=new Un(a);super(l,{name:"Reka",apiURL:o||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:r,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,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:s})}};var Bn=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),o=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(o,t),routing:n}}catch(r){if(r instanceof V&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw r}}async preprocessRequest(e,t,n){let o={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},r=[];for(let s of e.chatPrompt)if(s.role==="user"&&Array.isArray(s.content)){let a=await Gn(s.content,t,o);a.every(p=>p.type==="text")&&a.length===1?r.push({...s,content:a[0].text}):r.push({...s,content:a.map(p=>({type:"text",text:p.text}))})}else r.push(s);return{...e,chatPrompt:r}}async selectProviderWithDegradation(e,t){let n=he(e),o=[],r=[],s=[];try{let a=yn(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(r.push("Images will be converted to text descriptions"),o.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(r.push("Audio will be transcribed to text"),o.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(r.push("File content will be extracted to text"),o.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(r.push("URL content will be pre-fetched"),o.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&s.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&s.push("Content caching not supported"),{provider:a,processingApplied:o,degradations:r,warnings:s}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let o of t)try{let r={provider:o,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},s=await this.preprocessRequest(e,o,{fallbackBehavior:"degrade"});return{response:await o.chat(s,n),routing:r}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=he(e),n=[],o=[];try{let r=await this.selectProviderWithDegradation(e,{});return r.degradations.length>0&&(n.push(...r.degradations),o.push("Consider using a provider that natively supports all media types")),r.warnings.length>0&&n.push(...r.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),o.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),o.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||r.degradations.length>0,issues:n,recommendations:o}}catch(r){return{canHandle:!1,issues:[`Cannot route request: ${r instanceof Error?r.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),o=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(o)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(o)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(o)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(o)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(o)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(o)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(o))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var qn=[];var Dr=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...O()}),ze=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Together API key not set");let s={...Dr(),...t};r=[...qn,...r??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:r,models:o,supportFor:a}),super.setName("Together")}};var kt=(c=>(c.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",c.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",c.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",c.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",c.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",c.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",c.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",c.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",c.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",c.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",c.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",c.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",c))(kt||{});var zn=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var Lr=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...O()}),di=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...N()}),jn=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(u=>u.type==="text").map(u=>u.text).join(`
155
+ `));let p={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...p,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:p}),o=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),r={name:"/chat/completions",localCall:async(a,l)=>{try{let p=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(u){try{for await(let d of p)u.enqueue(d);u.close()}catch(d){u.error(d)}}}):p}catch(p){throw new Error(`WebLLM API error: ${p}`)}}},s={model:t,messages:n,...o?.length?{tools:o}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[r,s]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,o)=>{let r="stop";switch(n.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let s=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:o,id:e.id,content:n.message.content||"",functionCalls:s,finishReason:r}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,o=e.choices[0];if(!o)throw new Error("No choice in WebLLM stream response");if(o.delta.content&&(n.content=(n.content||"")+o.delta.content),o.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of o.delta.tool_calls){let p=n.toolCalls[l.index];p?l.function?.arguments&&(p.function.arguments=(p.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let r;if(o.finish_reason)switch(o.finish_reason){case"stop":r="stop";break;case"length":r="length";break;case"tool_calls":r="function_call";break;case"content_filter":r="content_filter";break;default:r="stop";break}let s=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:s,finishReason:r}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},je=class extends D{constructor({engine:e,config:t,options:n,models:o}){if(!e)throw new Error("WebLLM engine instance is required");let r={...Lr(),...t},s=new jn(r,e);super(s,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:zn,defaults:{model:r.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:o})}};var Et=(o=>(o.Grok3="grok-3",o.Grok3Mini="grok-3-mini",o.Grok3Fast="grok-3-fast",o.Grok3MiniFast="grok-3-mini-fast",o))(Et||{}),Nr=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Nr||{});var Hn=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var Kn=()=>structuredClone({model:"grok-3-mini",...O()}),mi=()=>structuredClone({...Kn(),model:"grok-3"}),He=class extends _{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Grok API key not set");let s={...Kn(),...t};r=[...Hn,...r??[]];let a=p=>{let u=W({model:p,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=p=>{if(n?.searchParameters){let u=n.searchParameters;return{...p,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))}}}return p};super({apiKey:e,config:s,options:n,apiURL:"https://api.x.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function gi(i){return Pt.create(i)}var Pt=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new Me(e);break;case"openai-responses":this.ai=new Ue(e);break;case"azure-openai":this.ai=new ke(e);break;case"grok":this.ai=new He(e);break;case"huggingface":this.ai=new Le(e);break;case"groq":this.ai=new De(e);break;case"together":this.ai=new ze(e);break;case"openrouter":this.ai=new Be(e);break;case"cohere":this.ai=new Ee(e);break;case"google-gemini":this.ai=new Fe(e);break;case"anthropic":this.ai=new we(e);break;case"mistral":this.ai=new Ne(e);break;case"deepseek":this.ai=new Pe(e);break;case"ollama":this.ai=new Ge(e);break;case"reka":this.ai=new qe(e);break;case"webllm":this.ai=new je(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};import{SpanKind as Wn}from"@opentelemetry/api";var Q=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Wn.SERVER,attributes:{[v.DB_SYSTEM]:this.name,[v.DB_OPERATION_NAME]:"upsert",[v.DB_TABLE]:e.table,[v.DB_NAMESPACE]:e.namespace,[v.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Wn.SERVER,attributes:{[v.DB_SYSTEM]:this.name,[v.DB_OPERATION_NAME]:"upsert",[v.DB_TABLE]:e[0].table,[v.DB_NAMESPACE]:e[0].namespace,[v.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Wn.SERVER,attributes:{[v.DB_SYSTEM]:this.name,[v.DB_OPERATION_NAME]:"upsert",[v.DB_TABLE]:e.table,[v.DB_NAMESPACE]:e.namespace,[v.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Vn="https://api.cloudflare.com/client/v4/accounts/",Ke=class extends Q{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:o}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:o}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let o=await q({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(o.errors)throw new Error(`Cloudflare upsert failed: ${o.errors.map(({message:r})=>r).join(", ")}`);return{ids:o.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let o=e[0].table,r=await q({url:new URL(`${this.accountId}/vectorize/indexes/${o}/upsert`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(s=>({id:s.id,values:s.values,namespace:s.namespace,metadata:s.metadata})));if(r.errors)throw new Error(`Cloudflare batch upsert failed: ${r.errors.map(({message:s})=>s).join(", ")}`);return{ids:r.result.ids}};query=async(e,t)=>{let n=await q({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Vn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:r})=>r).join(", ")}`);return{matches:n.result.matches.map(({id:r,score:s,values:a,metadata:l})=>({id:r,score:s,values:a,metadata:l}))}}};var ie=class extends Q{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let o=this.state[e.table];if(!o)throw new Error(`Table not found: ${e.table}`);o[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let o=[];for(let r of e){let s=await this.upsert(r,t);o.push(...s.ids)}return{ids:o}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let o=[];return Object.entries(n).forEach(([r,s])=>{if(e.values&&s.values){let a=hi(e.values,s.values);o.push({id:r,score:a,metadata:s.metadata})}}),o.sort((r,s)=>r.score-s.score),e.limit&&(o.length=e.limit),{matches:o}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},hi=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,o=0,r=!0,s=!0,a=new Float64Array(i),l=new Float64Array(e);for(let c=0;c<a.length;c++)t+=a[c]*l[c],n+=a[c]*a[c],o+=l[c]*l[c],a[c]!==0&&(r=!1),l[c]!==0&&(s=!1);if(r||s)return 1;let p=Math.sqrt(n),u=Math.sqrt(o);return 1-t/(p*u)};var fi=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),We=class extends Q{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await q({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:o,values:r=[],metadata:s})=>({id:o,values:r,metadata:s}))),{ids:e.map(({id:o})=>o)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await q({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},fi(e))).matches.map(({id:r,score:s,values:a,metadata:l})=>({id:r,score:s,metadata:l,values:a}))}}};var Ve=class extends Q{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:o}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let o=await q({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(o?.result?.errors)throw new Error(`Weaviate upsert failed: ${o.result.errors.error.map(({message:r})=>r).join(", ")}`);return{ids:[o.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let o=e.map(s=>({id:s.id,class:s.table,tenant:s.namespace,vector:s.values,properties:s.metadata??{}})),r=await q({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:o});if(r?.some(({result:s})=>s?.errors))throw new Error(`Weaviate batch upsert failed: ${r.map(({result:s})=>s?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:r.map(({id:s})=>s)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
156
156
  vector: [${e.values.join(",")}],
157
157
  }`;else if(e.text)n=`nearText: {
158
158
  concepts: ['${e.text}'],
159
- }`;else throw new Error("Weaviate requires either text or values");let o=await z({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
159
+ }`;else throw new Error("Weaviate requires either text or values");let o=await q({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
160
160
  Get {
161
161
  ${e.table} (
162
162
  limit: ${e.limit||10},
@@ -168,7 +168,7 @@ ${p}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
168
168
  }
169
169
  }`});if(o.errors)throw new Error(`Weaviate query failed: ${o.errors.map(({message:a})=>a).join(", ")}`);let r=o.data.Get[e.table];return r?{matches:r.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var Jn=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Ve(e);break;case"pinecone":this.db=new We(e);break;case"cloudflare":this.db=new Ke(e);break;case"memory":this.db=new ie(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var Qn="_internal",Yn=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
170
170
 
171
- `):e,o=this.chunker(n).filter(p=>p.length>0),r=t?.maxWordsPerChunk,s=t?.minWordsPerChunk,a=xi({initialChunks:o,minWordsPerChunk:s,maxWordsPerChunk:r}),l=t?.batchSize??10;for(let p=0;p<a.length;p+=l){let u=a.slice(p,p+l),d=(await this.ai.embed({texts:u},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:Qn,values:m,metadata:{text:u[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(d)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let o=Array.isArray(e)?e:[e];if(typeof o[0]=="string"&&this.rewriter)for(let[l,p]of o.entries()){let{rewrittenQuery:u}=await this.rewriter.forward(this.ai,{query:p});o[l]=u}let r;typeof o[0]=="string"?r=(await this.ai.embed({texts:o},{abortSignal:n})).embeddings.map(p=>this.db.query({table:Qn,values:p})):r=o.map(l=>this.db.query({table:Qn,values:l}));let s=await Promise.all(r),a=[];for(let{matches:l}of s){let p=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),u=t&&t>1?t/100:t,c=u?yi(p,u):p;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:o[0],items:c.map(g=>g.text)}),m=d.map(g=>c.find(h=>h.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(c)}return a}},xi=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],o="",r=0;return i.forEach(s=>{let a=s.split(/\s+/),l=a.length;if(r+l<=e)o+=`${s}
171
+ `):e,o=this.chunker(n).filter(p=>p.length>0),r=t?.maxWordsPerChunk,s=t?.minWordsPerChunk,a=Ai({initialChunks:o,minWordsPerChunk:s,maxWordsPerChunk:r}),l=t?.batchSize??10;for(let p=0;p<a.length;p+=l){let u=a.slice(p,p+l),c=(await this.ai.embed({texts:u},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:Qn,values:m,metadata:{text:u[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(c)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let o=Array.isArray(e)?e:[e];if(typeof o[0]=="string"&&this.rewriter)for(let[l,p]of o.entries()){let{rewrittenQuery:u}=await this.rewriter.forward(this.ai,{query:p});o[l]=u}let r;typeof o[0]=="string"?r=(await this.ai.embed({texts:o},{abortSignal:n})).embeddings.map(p=>this.db.query({table:Qn,values:p})):r=o.map(l=>this.db.query({table:Qn,values:l}));let s=await Promise.all(r),a=[];for(let{matches:l}of s){let p=l.filter(c=>c.metadata?.text&&c.metadata?.text.length>0).map(({score:c,metadata:m})=>({score:c,text:m?.text??""})),u=t&&t>1?t/100:t,d=u?xi(p,u):p;if(this.reranker){let{rankedItems:c}=await this.reranker.forward(this.ai,{query:o[0],items:d.map(g=>g.text)}),m=c.map(g=>d.find(h=>h.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(d)}return a}},Ai=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],o="",r=0;return i.forEach(s=>{let a=s.split(/\s+/),l=a.length;if(r+l<=e)o+=`${s}
172
172
 
173
173
  `,r+=l;else if(r>0&&r+l<=e*1.5)o+=`${s}
174
174
 
@@ -176,7 +176,7 @@ ${p}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
176
176
 
177
177
  `,r+=p.length)}else o=`${s}
178
178
 
179
- `,r=l}),(r>t||n.length===0)&&n.push(o.trim()),n},yi=(i,e=.1)=>{let t=[...i].sort((o,r)=>o.score-r.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as Ki,SpanKind as Wi,trace as Vi}from"@opentelemetry/api";var Je=class{data=[];addRequest(e,t){this.data.push(...e.map(n=>{let o=structuredClone(n);return{role:n.role,chat:[{index:t,value:o}]}}))}addFunctionResults(e){let t=e.map(({index:o,...r})=>({index:o,value:structuredClone(r)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...o})=>({index:n,value:structuredClone(o)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:o}){let r=this.data.at(-1);if(!r||r.role!=="assistant"||r.role==="assistant"&&!r.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:o,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let s=r.chat.find(a=>a.index===o);if(!s){r.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(s.value.content=e),typeof t=="string"&&t.trim()!==""&&(s.value.name=t),Array.isArray(n)&&n.length>0&&(s.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,o,r)=>(o.tags?.includes(e)&&n.push(r),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:o}of this.data){let r;n==="function"?r=o.filter(s=>s.index===e).map(s=>s.value):r=o.find(s=>s.index===e)?.value,Array.isArray(r)&&r.length>0?t.push(...r.map(s=>({...s,role:n}))):typeof r=="object"&&r!==null&&t.push({...r,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}},Qe=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Je}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Je),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ce(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){pn(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Je):this.defaultMemory.reset()}};var ae=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Ft=async(i,e)=>{for(let t of i){let{fn:n,message:o}=t,r=await n(e);if(r!==void 0&&!r)throw o?new ae({message:o}):new Error("Assertion Failed: No message provided for assertion")}},Xn=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let o=i.filter(s=>s.fieldName===e.currField?.name);if(o.length===0)return;let r=t.substring(e.s);for(let s of o){let{message:a,fn:l}=s,p=await l(r,n);if(p!==void 0&&!p&&a)throw new ae({message:a})}};var $r={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Ye,Zn=i=>{if(Ye)return Ye;let e=i??M.meter;if(e)return Ye=bi(e),Ye};var Ii=()=>{let i=[];return M.meter||i.push("Global meter not initialized"),!Ye&&M.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},bi=i=>({generationLatencyHistogram:i.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:i.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:i.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:i.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:i.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:i.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:i.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:i.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:i.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:i.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:i.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:i.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:i.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:i.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:i.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:i.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:i.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:i.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:i.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:i.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:i.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:i.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:i.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:i.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:i.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:i.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:i.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:i.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:i.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:i.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:i.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:i.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:i.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),_t=$r,Ti=i=>{_t={..._t,...i}},Ri=()=>({..._t}),Y=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n),r=_t.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},Gr=(i,e,t,n,o,r)=>{try{let s=Y({success:t.toString(),...n?{signature:n}:{},...o?{ai_service:o}:{},...r?{model:r}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Dt=(i,e,t,n)=>{try{let o=Y({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,o),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,o),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},eo=(i,e,t)=>{try{let n=Y({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},Ur=(i,e)=>{try{let t=Y({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},to=(i,e,t,n,o)=>{try{let r=Y({success:t.toString(),...o?{signature:o}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,r),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,r),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,r),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,r))}catch(r){console.warn("Failed to record error correction metric:",r)}},Br=(i,e,t,n,o=!1,r)=>{try{let s=Y({functions_enabled:e.toString(),had_function_calls:n.toString(),...r?{signature:r}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),o&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},qr=(i,e,t,n)=>{try{let o=Y({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,o),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},zr=(i,e,t,n,o)=>{try{let r=Y({is_streaming:e.toString(),...o?{signature:o}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,r),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,r),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record streaming metric:",r)}},jr=(i,e,t,n,o)=>{try{let r=Y({result_picker_used:t.toString(),...o?{signature:o}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,r),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,r),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record samples metric:",r)}},Hr=(i,e,t,n,o,r)=>{try{let s=Y({...r?{signature:r}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(o,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},Lt=(i,e,t,n)=>{try{let o=Y({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,o);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,o);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,o);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var N=class extends Error{fields;constructor({message:e,fields:t}){super(e),this.fields=t,this.name=this.constructor.name}getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))};toString(){let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
179
+ `,r=l}),(r>t||n.length===0)&&n.push(o.trim()),n},xi=(i,e=.1)=>{let t=[...i].sort((o,r)=>o.score-r.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as Hi,SpanKind as Ki,trace as Wi}from"@opentelemetry/api";var Je=class{data=[];addRequest(e,t){this.data.push(...e.map(n=>{let o=structuredClone(n);return{role:n.role,chat:[{index:t,value:o}]}}))}addFunctionResults(e){let t=e.map(({index:o,...r})=>({index:o,value:structuredClone(r)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...o})=>({index:n,value:structuredClone(o)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:o}){let r=this.data.at(-1);if(!r||r.role!=="assistant"||r.role==="assistant"&&!r.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:o,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let s=r.chat.find(a=>a.index===o);if(!s){r.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(s.value.content=e),typeof t=="string"&&t.trim()!==""&&(s.value.name=t),Array.isArray(n)&&n.length>0&&(s.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,o,r)=>(o.tags?.includes(e)&&n.push(r),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:o}of this.data){let r;n==="function"?r=o.filter(s=>s.index===e).map(s=>s.value):r=o.find(s=>s.index===e)?.value,Array.isArray(r)&&r.length>0?t.push(...r.map(s=>({...s,role:n}))):typeof r=="object"&&r!==null&&t.push({...r,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}},Qe=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Je}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Je),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ce(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){pn(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Je):this.defaultMemory.reset()}};var ae=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Ft=async(i,e)=>{for(let t of i){let{fn:n,message:o}=t,r=await n(e);if(r!==void 0&&!r)throw o?new ae({message:o}):new Error("Assertion Failed: No message provided for assertion")}},Xn=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let o=i.filter(s=>s.fieldName===e.currField?.name);if(o.length===0)return;let r=t.substring(e.s);for(let s of o){let{message:a,fn:l}=s,p=await l(r,n);if(p!==void 0&&!p&&a)throw new ae({message:a})}};var Gr={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Ye,Zn=i=>{if(Ye)return Ye;let e=i??M.meter;if(e)return Ye=Ii(e),Ye};var yi=()=>{let i=[];return M.meter||i.push("Global meter not initialized"),!Ye&&M.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},Ii=i=>({generationLatencyHistogram:i.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:i.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:i.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:i.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:i.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:i.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:i.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:i.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:i.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:i.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:i.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:i.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:i.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:i.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:i.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:i.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:i.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:i.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:i.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:i.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:i.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:i.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:i.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:i.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:i.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:i.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:i.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:i.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:i.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:i.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:i.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:i.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:i.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),_t=Gr,bi=i=>{_t={..._t,...i}},Ti=()=>({..._t}),Y=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n),r=_t.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},$r=(i,e,t,n,o,r)=>{try{let s=Y({success:t.toString(),...n?{signature:n}:{},...o?{ai_service:o}:{},...r?{model:r}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Dt=(i,e,t,n)=>{try{let o=Y({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,o),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,o),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},eo=(i,e,t)=>{try{let n=Y({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},Ur=(i,e)=>{try{let t=Y({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},to=(i,e,t,n,o)=>{try{let r=Y({success:t.toString(),...o?{signature:o}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,r),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,r),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,r),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,r))}catch(r){console.warn("Failed to record error correction metric:",r)}},Br=(i,e,t,n,o=!1,r)=>{try{let s=Y({functions_enabled:e.toString(),had_function_calls:n.toString(),...r?{signature:r}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),o&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},qr=(i,e,t,n)=>{try{let o=Y({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,o),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},zr=(i,e,t,n,o)=>{try{let r=Y({is_streaming:e.toString(),...o?{signature:o}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,r),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,r),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record streaming metric:",r)}},jr=(i,e,t,n,o)=>{try{let r=Y({result_picker_used:t.toString(),...o?{signature:o}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,r),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,r),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record samples metric:",r)}},Hr=(i,e,t,n,o,r)=>{try{let s=Y({...r?{signature:r}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(o,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},Lt=(i,e,t,n)=>{try{let o=Y({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,o);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,o);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,o);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var G=class extends Error{fields;constructor({message:e,fields:t}){super(e),this.fields=t,this.name=this.constructor.name}getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))};toString(){let e=t=>{let n=(()=>{switch(t?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return t?.isArray?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
180
180
  `)}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Kr=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(p=>p.title).join(", ")??"";Wo(i,e,l,n)}return o&&eo(o,"validation",r),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Wr=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(p=>p.title).join(", ")??"";Vo(i,e,l,n)}return o&&eo(o,"assertion",r),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Vr=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:s})=>{t&&n&&Jo(i,e,n),o&&Ur(o,r),s&&s.addEvent("refusal.error",{message:i.toString()})};var Jr=i=>{let e=[],t=(n,o="")=>{if(!n||typeof n!="object")return;let r=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:o||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((s,a)=>{t(s,`${o}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:o||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((s,a)=>{t(s,`${o}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:o||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((s,a)=>{t(s,`${o}allOf[${a}].`)});return}if(n.type){if(!r.includes(n.type)){e.push({path:o||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${r.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:o||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let s in n.properties){let a=n.properties[s];if(a!=null){if(typeof a!="object"){e.push({path:`${o}${s}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${s}: { type: "string", description: "..." }`});continue}t(a,`${o}${s}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:o||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let s of n.required)typeof s!="string"?e.push({path:`${o}required`,issue:`Required property names must be strings, got ${typeof s}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):s in n.properties||e.push({path:`${o}required`,issue:`Required property '${s}' is not defined in properties`,fix:`Either add '${s}' to properties or remove it from required`,example:`properties: { ${s}: { type: "string" } }`})}}}n.type==="array"&&(n.items?typeof n.items!="object"?e.push({path:`${o}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${o}items.`):e.push({path:o||"root",issue:'Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)',fix:'Add an "items" schema describing the array element type, e.g., items: { type: "string" } or items: { type: "object", properties: { ... } }',example:['type: "array",','description: "List of step strings"','items: { type: "string" }'].join(`
181
181
  `)}))}};if(t(i),e.length>0){let n=["JSON Schema validation failed:","",...e.map((o,r)=>{let s=[`${r+1}. Path: ${o.path}`,` Issue: ${o.issue}`,` Fix: ${o.fix}`];return o.example&&s.push(` Example: ${o.example}`),s.join(`
182
182
  `)}),"","Please fix these issues and try again."].join(`
@@ -184,57 +184,56 @@ ${p}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
184
184
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Xe=class extends Error{constructor(t,n,o){super();this.fields=t;this.func=n;this.funcId=o}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],o=n.description;return n.enum?.length&&(o+=` Allowed values are: ${n.enum.join(", ")}`),o}getFixingInstructions=()=>{let t=this.fields.map(n=>{let o=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${o}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
185
185
  ${t.join(`
186
186
  `)}`};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(`
187
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},$t=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let o;typeof t.args=="string"&&t.args.length>0?o=JSON.parse(t.args):o=t.args;let r=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;return e.parameters?s=e.func.length===2?await e.func(o,r):await e.func(o):s=e.func.length===1?await e.func(r):await e.func(),(n?.functionResultFormatter??M.functionResultFormatter)(s)};execute=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),o=n(e.name),r=this.funcList.find(s=>s.name===e.name);if(r||(r=this.funcList.find(s=>n(s.name)===o)),!r)throw new Error(`Function not found: ${e.name}`);if(!r.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(r,e,t)}catch(s){throw s instanceof Nt?new Xe(s.getFields(),r,e.id):s}}},no=(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(o=>o.parameters))if(n.parameters)try{Jr(n.parameters)}catch(o){throw o instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
187
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Gt=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let o;typeof t.args=="string"&&t.args.length>0?o=JSON.parse(t.args):o=t.args;let r=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;return e.parameters?s=e.func.length===2?await e.func(o,r):await e.func(o):s=e.func.length===1?await e.func(r):await e.func(),(n?.functionResultFormatter??M.functionResultFormatter)(s)};execute=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),o=n(e.name),r=this.funcList.find(s=>s.name===e.name);if(r||(r=this.funcList.find(s=>n(s.name)===o)),!r)throw new Error(`Function not found: ${e.name}`);if(!r.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(r,e,t)}catch(s){throw s instanceof Nt?new Xe(s.getFields(),r,e.id):s}}},no=(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(o=>o.parameters))if(n.parameters)try{Jr(n.parameters)}catch(o){throw o instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
188
188
  ${o.message}
189
- Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:o}):o}return[...e??[],...t]},oo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:o,traceId:r,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:p,logger:u})=>{let c=new $t(e),d=new Set,m=t.map(f=>{if(!f.id)throw new Error(`Function ${f.name} did not return an ID`);let I=i.getOptions().tracer??M.tracer;return I?I.startActiveSpan(`Tool: ${f.name}`,async A=>{try{A?.setAttributes?.({"tool.name":f.name,"tool.mode":"native","function.id":f.id,"session.id":o??""});let b=await c.execute(f,{sessionId:o,ai:i,functionResultFormatter:p,traceId:A?.spanContext?.().traceId??r});if(d.add(f.name.toLowerCase()),a?A.addEvent("gen_ai.tool.message",{name:f.name}):A.addEvent("gen_ai.tool.message",{name:f.name,args:f.args,result:b??""}),s){let R={name:f.name};a||(R.args=f.args,R.result=b??""),s.addEvent("function.call",R)}return{result:b??"",role:"function",functionId:f.id,index:l}}catch(b){if(A?.recordException?.(b),b instanceof Xe){let R=b.getFixingInstructions(),y={name:f.name,message:b.toString()};return a||(y.args=f.args,y.fixing_instructions=R),A?.addEvent?.("function.error",y),i.getOptions().debug&&on(b,l,R,u),{functionId:f.id,isError:!0,index:l,result:R,role:"function"}}throw b}finally{A?.end?.()}}):c.execute(f,{sessionId:o,ai:i,functionResultFormatter:p,traceId:r}).then(A=>{if(d.add(f.name.toLowerCase()),s){let b={name:f.name};a||(b.args=f.args,b.result=A??""),s.addEvent("function.call",b)}return{result:A??"",role:"function",functionId:f.id,index:l}}).catch(A=>{if(!(A instanceof Xe))throw A;let b=A.getFixingInstructions();if(s){let R={name:f.name,message:A.toString()};a||(R.args=f.args,R.fixing_instructions=b),s.addEvent("function.error",R)}return i.getOptions().debug&&on(A,l,b,u),{functionId:f.id,isError:!0,index:l,result:b,role:"function"}})}),h=(await Promise.all(m)).filter(f=>f!==void 0);if(n.addFunctionResults(h,o),i.getOptions().debug){let f=h.filter(I=>!I.isError);f.length>0&&Ko(f,u)}return h.some(f=>f.isError)&&n.addTag("error",o),d};function ro(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(r=>({id:r.id,name:r.function.name,args:r.function.params}))}function Qr(i,e,t,n){let o=e;return n?.functionCallMode==="prompt"?{functions:[],functionCall:void 0}:!t&&(o==="required"||typeof o=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:o}:{functions:[],functionCall:o}}import le from"dayjs";import Ci from"dayjs/plugin/customParseFormat.js";import wi from"dayjs/plugin/timezone.js";import Si from"dayjs/plugin/utc.js";le.extend(Si);le.extend(wi);le.extend(Ci);function Yr(i,e,t=!1){try{return vi(e)}catch(n){if(i.isOptional&&!t)return;let o=n.message;throw new N({fields:[i],message:o,value:e})}}function vi(i){if(!le(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return le.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Xr(i,e,t=!1){try{return Oi(e)}catch(n){if(i.isOptional&&!t)return;let o=n.message;throw new N({fields:[i],message:o,value:e})}}function Oi(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,o]=t;if(!n||!o)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 r=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=le.tz(n,r,o);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 ${o}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Zr=i=>le(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Nc=new $;var Gt=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(p,u)=>{switch(p){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";default:return!1}},o=p=>!(!p||typeof p!="object"||!("mimeType"in p)||!("data"in p));if(i.type?.name==="image"){let p;if(Array.isArray(e)){for(let u of e)if(!o(u)){p="object ({ mimeType: string; data: string })";break}}else o(e)||(p="object ({ mimeType: string; data: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let r=p=>!(!p||typeof p!="object"||!("data"in p));if(i.type?.name==="audio"){let p;if(Array.isArray(e)){for(let u of e)if(!r(u)){p="object ({ data: string; format?: string })";break}}else r(e)||(p="object ({ data: string; format?: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let s=p=>{if(!p||typeof p!="object"||!("mimeType"in p))return!1;let u="data"in p,c="fileUri"in p;return!(!u&&!c||u&&c)};if(i.type?.name==="file"){let p;if(Array.isArray(e)){for(let u of e)if(!s(u)){p="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(p="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let a=p=>typeof p=="string"?!0:!(!p||typeof p!="object"||!("url"in p));if(i.type?.name==="url"){let p;if(Array.isArray(e)){for(let u of e)if(!a(u)){p="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(p="string or object ({ url: string; title?: string; description?: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let p of e)if(!n(t.name,p)){l=!1;break}}else l=n(t.name,e);if(!l){let p=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${p}' (${JSON.stringify(e)})`)}};function Ze(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let o=e[n];if(o){let r=o.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};r.promptTokens+=t?.tokens?.promptTokens??0,r.completionTokens+=t?.tokens?.completionTokens??0,r.totalTokens+=t?.tokens?.totalTokens??0,o.tokens=r;let s=o.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(p=>p.url));for(let p of a)p?.url&&!l.has(p.url)&&(s.push(p),l.add(p.url));o.citations=s}}}return Object.values(e)}var es=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
190
- `),o=[];for(let r of n){let s=r.trim();if(s){if(s[0]&&e.has(s[0]))o.push(s.slice(1).trim());else if(t.test(s))o.push(s.replace(t,"").trim());else if(o.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(o.length===0)throw new Error("Could not parse markdown list: no valid list items found");return o};function io(i,e){let{index:t,delta:n,version:o}=e,r=i.find(s=>s.index===t)?.delta;if(!r)return i.push({index:t,delta:n,version:o}),i;for(let s of Object.keys(n)){let a=r[s],l=n[s];a===void 0&&Array.isArray(l)?r[s]=[...l]:Array.isArray(a)&&Array.isArray(l)?r[s]=[...a,...l]:(a===void 0||typeof a=="string")&&typeof l=="string"?r[s]=`${a??""}${l}`:r[s]=l}return i}var so=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)}},Mi=new so(500);function ao(i,e,t=0,n=Mi){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let o=i.indexOf(e,t);if(o!==-1)return o;let r=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,r);let s=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}var os=(i,e,t,n=!1)=>{let o={extractedFields:[],streamedIndex:{},s:-1};lo(i,e,o,t,{strictMode:n}),po(i,e,o,t,n);for(let r of i.getOutputFields())r.isInternal&&delete e[r.name]},ki=(i,e,t)=>{let n=[];for(let o of t)o&&!o.isOptional&&e[o.name]===void 0&&n.push(o);if(n.length>0)throw new N({message:`Required ${n.length===1?"field":"fields"} not found`,fields:n})},lo=(i,e,t,n,{strictMode:o,skipEarlyFail:r}={})=>{let s=i.getOutputFields(),a;for(let[l,p]of s.entries()){if(l===t.currFieldIndex&&!t.inAssumedField||p.name in e&&!(l===t.currFieldIndex&&t.inAssumedField))continue;let c=`${(t.extractedFields.length===0?"":`
191
- `)+p.title}:`,d=ao(n,c,t.s),m=c.length;switch(d){case-1:if(r)continue;if(!o&&s.length===1&&t.currField===void 0){t.inAssumedField=!0,a=p,m=0,d=0;break}if(t.currField===void 0&&t.extractedFields.length===0){if(o&&!p.isOptional)throw new N({message:"Expected (Required) field not found",fields:[p]});if(!o){let g=!1;for(let h=l;h<s.length;h++){let f=s[h];if(!f)continue;let I=`${(t.extractedFields.length===0?"":`
192
- `)+f.title}:`;if(ao(n,I,t.s)>=0){g=!0;break}}if(!g){t.inAssumedField=!0,a=p,m=0,d=0;break}}}a=p.isOptional?void 0:p;continue;case-2:return!0;case-3:return!0;case-4:return t.inBlock=!0,!0}if(a&&a.name!==p.name)throw new N({message:"Expected (Required) field not found",fields:[a]});if(t.currField!==void 0&&t.inAssumedField){let g=n.substring(0,d).trim();if(g&&t.currField.name===p.name){let h=et(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}else if(g){let h=et(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0}if(t.currField){let g=n.substring(t.s,d).trim(),h=et(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,t.currField=p,t.currFieldIndex=l,t.extractedFields.includes(p)||t.extractedFields.push(p),t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},po=(i,e,t,n,o=!1)=>{if(t.currField){let r=n.substring(t.s).trim(),s=et(t.currField,r);s!==void 0&&(e[t.currField.name]=s)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let a=i.getOutputFields().find(l=>!l.isOptional);if(a)throw new N({message:"Expected field not found",fields:[a]})}Ei(i,e,n),ki(t,e,i.getOutputFields())},Ei=(i,e,t)=>{let n=i.getOutputFields();for(let o of n){if(!o.isOptional||o.name in e)continue;let r=`${o.title}:`,s=t.indexOf(r);if(s===-1)continue;let a=s+r.length,l=t.length;for(let u of n){if(u.name===o.name)continue;let c=`${u.title}:`,d=t.indexOf(c,a);d!==-1&&d<l&&(l=d)}let p=t.substring(a,l).trim();if(p)try{let u=et(o,p);u!==void 0&&(e[o.name]=u)}catch{}}},ts=(i,e,t=!1)=>{switch(i.type?.name){case"code":return rs(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 Yr(i,e,t);case"datetime":return Xr(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*ns(i,e,t,n,o,r){let{name:s,isInternal:a}=e,{isArray:l,name:p}=e.type??{};if(a||l||p&&p!=="string"&&p!=="code")return;let u=o.streamedIndex[s]??0,c=u===0,d=i.substring(t+u,n);if(d.length===0)return;let m=d.replace(/\s+$/,"");o.currField?.type?.name==="code"&&(m=m.replace(/\s*```\s*$/,""));let g=c?m.trimStart():m;o.currField?.type?.name==="code"&&(g=g.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),g.length>0&&(yield{index:r,delta:{[s]:g}},o.streamedIndex[s]=u+m.length)}function*uo(i,e,t,n,o){for(let s of n.prevFields??[]){let{field:a,s:l,e:p}=s;yield*ns(e,a,l,p,n,o)}if(n.prevFields=void 0,!n.currField||n.currField.isInternal)return;yield*ns(e,n.currField,n.s,e.length,n,o);let r=i.getOutputFields();for(let s of Object.keys(t)){let a=r.find(p=>p.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let p=n.streamedIndex?.[s]??0,u=l.slice(p);u&&u.length>0&&(yield{index:o,delta:{[s]:u}},n.streamedIndex[s]=p+u.length);continue}n.streamedIndex[s]||(yield{index:o,delta:{[s]:l}},n.streamedIndex[s]=1)}}function et(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw new N({message:"Required field is missing",fields:[i],value:e})}let t;if(i.type?.name==="json")try{let n=rs(e);return t=JSON.parse(n),t}catch(n){throw new N({message:`Invalid JSON: ${n.message}`,fields:[i],value:e})}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=es(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw new N({message:`Invalid Array: ${n.message}`,fields:[i],value:e})}try{if(Array.isArray(t)){for(let[n,o]of t.entries())if(o!==void 0){let r=typeof o=="string"?o.trim():o;t[n]=ts(i,r,!0)}}else t=ts(i,e)}catch(n){throw new N({message:n.message,fields:[i],value:e})}if(!(typeof t=="string"&&t===""))return t}var rs=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function co(i,e,t,n){for(let o of i){if(e[o.field.name]===void 0)continue;let r=o.process,s=await r(e[o.field.name],{sessionId:n,values:e,done:!0});ss(o.field,t,s,n)}}async function mo(i,e,t,n,o,r,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 p=a.process,u=await p(l,{sessionId:r,values:o,done:s});ss(t.currField,n,u,r)}}var ss=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let o=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),r=Pi(i,o);e.addRequest([{role:"user",content:[{type:"text",text:r}]}],n),e.addTag("processor",n)};function Pi(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*is({res:i,usage:e,states:t,...n}){let o=(n.ai.getFeatures().functionCot??!1)&&n.functions!==void 0&&n.functions.length>0,r,s=[],a=i.getReader();try{for(;;){let{done:l,value:p}=await a.read();if(l)break;let u=p;u.modelUsage&&(r=u.modelUsage);for(let c of u.results){if(Array.isArray(c.citations))for(let m of c.citations)m?.url&&s.push({url:m.url,title:m.title,description:m.description,license:m.license,publicationDate:m.publicationDate,snippet:m.snippet});if((!c.content||c.content==="")&&(!c.thought||c.thought==="")&&(!c.functionCalls||c.functionCalls.length===0))continue;let d=t.find(m=>m.index===c.index);if(!d)throw new Error(`No state found for result (index: ${c.index})`);yield*Fi({...n,result:c,skipEarlyFail:o,state:d})}}}finally{a.releaseLock()}for(let l of t)yield*_i({...n,state:l});if(r){if(s.length){let l=Array.from(new Map(s.filter(p=>p.url).map(p=>[p.url,p])).values());r.citations=l}if(e.push(r),n.logger){let l=structuredClone(r);delete l.citations,n.logger({name:"ChatResponseUsage",value:l}),r.citations&&r.citations.length>0&&n.logger({name:"ChatResponseCitations",value:r.citations})}}}async function*Fi({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:o,state:r,signature:s,streamingFieldProcessors:a,thoughtFieldName:l,streamingAsserts:p,asserts:u}){if(i.functionCalls&&i.functionCalls.length>0)mt(r.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:r.functionCalls,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){if(i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[l]:i.thought}}),r.content+=i.content,e.updateResult({name:i.name,content:r.content,delta:i.content,index:i.index},t),lo(s,r.values,r.xstate,r.content,{strictMode:n,skipEarlyFail:o}))return;p.length!==0&&await Xn(p,r.xstate,r.content),a.length!==0&&await mo(a,r.content,r.xstate,e,r.values,t),yield*uo(s,r.content,r.values,r.xstate,i.index),await Ft(u,r.values)}else i.thought&&i.thought.length>0&&(r.values[l]=(r.values[l]??"")+i.thought,yield{index:i.index,delta:{[l]:i.thought}});if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
193
- Content: ${r.content}`)}async function*_i({state:i,signature:e,ai:t,model:n,functions:o,mem:r,sessionId:s,traceId:a,span:l,strictMode:p,excludeContentFromTrace:u,streamingAsserts:c,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,logger:f}){let I=ro(t,i.functionCalls,i.values,n);if(I){if(!o)throw new Error("Functions are not defined");let A=await oo({ai:t,functionList:o,functionCalls:I,mem:r,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:f});i.functionsExecuted=new Set([...i.functionsExecuted,...A]),i.functionCalls=[]}else po(e,i.values,i.xstate,i.content,p),await Xn(c,i.xstate,i.content,!0),await Ft(d,i.values),m.length&&await co(m,i.values,r,s),g.length!==0&&await mo(g,i.content,i.xstate,r,i.values,s,!0),yield*uo(e,i.content,i.values,i.xstate,i.index)}async function*as({ai:i,res:e,mem:t,sessionId:n,traceId:o,functions:r,span:s,strictMode:a,states:l,usage:p,excludeContentFromTrace:u,asserts:c,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:f}){let I=e.results??[];t.addResponse(I,n);let A=[];for(let x of I)if(Array.isArray(x?.citations))for(let T of x.citations)T?.url&&A.push({url:T.url,title:T.title,description:T.description,license:T.license,publicationDate:T.publicationDate,snippet:T.snippet});for(let x of I){let T=l[x.index];if(!T)throw new Error(`No state found for result (index: ${x.index})`);if(e.modelUsage){let v=Array.from(new Map(A.filter(P=>P.url).map(P=>[P.url,P])).values()),k={...e.modelUsage,...v.length?{citations:v}:{}};if(p.push(k),f){let P=structuredClone(k);delete P.citations,f({name:"ChatResponseUsage",value:P}),k.citations&&k.citations.length>0&&f({name:"ChatResponseCitations",value:k.citations})}}if(x.functionCalls?.length){let v=ro(i,x.functionCalls,T.values);if(v){if(!r)throw new Error("Functions are not defined");let k=await oo({ai:i,functionList:r,functionCalls:v,mem:t,sessionId:n,traceId:o,span:s,excludeContentFromTrace:u,index:x.index,functionResultFormatter:h,logger:f});T.functionsExecuted=new Set([...T.functionsExecuted,...k])}}else x.content&&(x.thought&&x.thought.length>0&&(T.values[m]=x.thought),os(g,T.values,x.content,a),await Ft(c,T.values),d.length&&await co(d,T.values,t,n));if(x.finishReason==="length")throw new Error(`Max tokens reached before completion
194
- Content: ${x.content}`)}let b=l.map(x=>x.values);for(let x of b)for(let T of g.getOutputFields())T.isInternal&&delete x[T.name];let R=g.getOutputFields(),y=b.map((x,T)=>{let v={};for(let k of R)k.isInternal||(v[k.name]=x[k.name]);return x[m]!==void 0&&(v[m]=x[m]),{index:T,delta:v}});for(let x of y)yield x}function ls(i,e,t,n){let o=i.getLast(n);if(!o)return!0;for(let[r,s]of t.entries()){let a=e&&s.functionsExecuted.has(e);if(!o.chat[r])throw new Error(`No chat message found for result (index: ${r})`);let p=o.role==="function",u=o.tags?o.tags.some(c=>c==="processor"):!1;if(p&&e&&a||!(p||u))return!1}return!0}var tt=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 w=class extends Error{constructor(t,n,o,r){super(t);this.position=n;this.context=o;this.suggestion=r;this.name="SignatureValidationError"}},go=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new w("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 w("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 w('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 o=this.input.slice(this.position);throw new w(`Unexpected content after signature: "${o}"`,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 w)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new w(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let o of e.inputs){if(t.has(o.name))throw new w(`Duplicate input field name: "${o.name}"`,0,"","Each field name must be unique within the signature");t.add(o.name)}let n=new Set;for(let o of e.outputs){if(n.has(o.name))throw new w(`Duplicate output field name: "${o.name}"`,0,"","Each field name must be unique within the signature");n.add(o.name)}for(let o of e.outputs)if(t.has(o.name))throw new w(`Field name "${o.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 w("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new w("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),o=this.input.slice(this.position,t),r=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${o}"`,` ${r}`].join(`
195
- `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new w(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(o){throw o instanceof w?o:new w(`Invalid first ${t} field: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new w(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(o){throw o instanceof w?o:new w(`Invalid ${t} field after comma: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new w(`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 w(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let r=this.parseTypeNotClass(),s=this.match("[]");n={name:r,isArray:s}}catch(r){throw r instanceof w?r:new w(`Input field "${e}": ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let o;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new w(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(p=>p.trim()).filter(p=>p.length>0);if(l.length===0)throw new w(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');o={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(o={name:s,isArray:a},s==="image"&&a)throw new w(`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 w(`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 w(`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 w(`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 w?s:new w(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:o,isOptional:t,isInternal:n}}validateFieldName(e,t){if(M.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 w(`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]*$/,o=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!o.test(e))throw new w(`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 w(`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 w(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",o=this.suggestType(n),r=`Invalid type "${n||"empty"}"`,s=o?`. Did you mean "${o}"?`:"",a=`${r}${s}`;throw new w(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 w("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 w(`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 w(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",o=!1,r=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,o)n+=a,o=!1;else if(a==="\\")o=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(r,Math.min(this.position,r+20));throw new w(`Unterminated string starting at position ${r}`,r,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 w(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function ps(i){return new go(i).parse()}var Bt=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let o={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.inputFields.unshift(o):this.inputFields.push(o),this}output(e,t,n=!1){let o={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.outputFields.unshift(o):this.outputFields.push(o),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new D(e)}},G=class i{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new i({...this,isOptional:!0})}array(){return new i({...this,isArray:!0})}internal(){return new i({...this,isInternal:!0})}},nt=Object.assign(()=>new Bt,{string:i=>new G({type:"string",isArray:!1,description:i}),number:i=>new G({type:"number",isArray:!1,description:i}),boolean:i=>new G({type:"boolean",isArray:!1,description:i}),json:i=>new G({type:"json",isArray:!1,description:i}),datetime:i=>new G({type:"datetime",isArray:!1,description:i}),date:i=>new G({type:"date",isArray:!1,description:i}),class:(i,e)=>new G({type:"class",isArray:!1,options:i,description:e}),image:i=>new G({type:"image",isArray:!1,description:i}),audio:i=>new G({type:"audio",isArray:!1,description:i}),file:i=>new G({type:"file",isArray:!1,description:i}),url:i=>new G({type:"url",isArray:!1,description:i}),code:(i,e)=>new G({type:"code",isArray:!1,description:e||i}),array:i=>({...i,isArray:!0}),optional:i=>({...i,isOptional:!0}),internal:i=>({...i,isInternal:!0}),legacyArray:i=>({...i,isArray:!0}),legacyOptional:i=>({...i,isOptional:!0}),legacyInternal:i=>({...i,isInternal:!0})});function Ut(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var C=class extends Error{constructor(t,n,o){super(t);this.fieldName=n;this.suggestion=o;this.name="AxSignatureValidationError"}},D=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=ps(e)}catch(n){if(n instanceof Error){let o="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new C(`Invalid Signature: ${n.message}`,void 0,o)}throw new C(`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);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new C("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 C("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 C?t:new C(`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 C("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 C("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 C("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 C("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);ne(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new C(`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 C(`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 C?t:new C(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ne(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new C(`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 C(`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 C?t:new C(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new C("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ne(o,"input"),o});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof C?t:new C(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new C("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ne(o,"output"),o});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof C?t:new C(`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,...Ut(t)}),n};prependInputField=(e,t)=>{let n=new i(this),o={name:e,...Ut(t)},r=n.parseField(o);ne(r,"input");for(let s of n.inputFields)if(s.name===r.name)throw new C(`Duplicate input field name: "${r.name}"`,r.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===r.name)throw new C(`Field name "${r.name}" appears in both inputs and outputs`,r.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(r),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Ut(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),o={name:e,...Ut(t)},r=n.parseField(o);ne(r,"output");for(let s of n.outputFields)if(s.name===r.name)throw new C(`Duplicate output field name: "${r.name}"`,r.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===r.name)throw new C(`Field name "${r.name}" appears in both inputs and outputs`,r.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(r),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let o of this.inputFields){let r=o.type?o.type.name:"string";o.type?.isArray?e[o.name]={description:o.description,type:"array",items:{type:r,description:o.description}}:e[o.name]={description:o.description,type:r},o.isOptional||t.push(o.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ne(e,"input")}),this.getOutputFields().forEach(e=>{ne(e,"output")}),this.sigHash=pt("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=cs(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof C?e:new C(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ne(e,"input")}),this.getOutputFields().forEach(e=>{ne(e,"output")}),this.validateSignatureConsistency(),this.sigHash=pt("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=cs(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof C?e:new C(`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 C(`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 C(`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 C(`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 C("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new C("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;injectToolFields(e){let t=new i(this);for(let n of e)if(n.parameters?.properties&&Object.keys(n.parameters.properties).length>0){let o=this.generateToolParameterFields(n);for(let r of o)t.outputFields.some(a=>a.name===r.name)||t.addOutputField(r)}else{let o=this.sanitizeFieldName(n.name),r=this.inferToolFieldType(n.parameters);t.outputFields.some(a=>a.name===o)||t.addOutputField({name:o,title:this.formatTitle(n.name),type:r,description:n.description||`Parameters for ${n.name}`,isOptional:!0})}return t}generateToolParameterFields(e){let t=[];if(!e.parameters||!e.parameters.properties)return t;let n=e.parameters.properties,o=e.parameters.required||[],r=(s,a,l)=>{for(let[p,u]of Object.entries(s)){let c=a?`${a}.${p}`:p,d=`${e.name}.${c}`;if(u.type==="object"&&u.properties)r(u.properties,c,u.required||[]);else{let m=this.inferParameterType(u);t.push({name:this.sanitizeFieldName(d),title:this.formatParameterTitle(e.name,c),type:m,description:u.description||`${p} parameter for ${e.name}`,isOptional:!0})}}};return r(n,"",o),t}inferParameterType(e){switch(e.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 t=e.items;if(t?.type)switch(t.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}}}formatParameterTitle(e,t){return`${e} ${t.replace(/\./g," ")}`}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}formatTitle(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}inferToolFieldType(e){return!e||!e.properties||Object.keys(e.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function us(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 cs(i,e,t){let n=i?`"${i}" `:"",o=e.map(us).join(", "),r=t.map(us).join(", ");return`${n}${o} -> ${r}`}function Di(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ne(i,e){if(!i.name||i.name.length===0)throw new C("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Di(i.name))throw new C(`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(M.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 C(`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 C(`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 C(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Li(i,e)}function Li(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new C(`${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 C("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 C("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let o of t.options){if(!o||o.trim().length===0)throw new C("Empty class option found",i.name,"All class options must be non-empty strings");let r=o.trim();if(r.includes(",")||r.includes("|"))throw new C(`Invalid class option "${r}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(o=>o.trim().toLowerCase())).size!==t.options.length)throw new C("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new C("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 C("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields")}var pe=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new D(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 tt,this.key={id:this.signature.hash()}}getSignature(){return new D(this.signature)}setSignature(e){this.signature=new D(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let o=this.signature,r=[...o.getInputFields(),...o.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of r){let p=s[l.name];p!==void 0&&(Gt(l,p),a[l.name]=p)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return Ze(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(o=>o.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(o=>o.programId===this.key.id).map(o=>o.traces).flat();for(let o of Array.from(this.children))o?.setDemos(e)}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 Ni=`
189
+ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:o}):o}return[...e??[],...t]},oo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:o,traceId:r,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:p,logger:u,debug:d})=>{let c=new Gt(e),m=new Set,g=t.map(f=>{if(!f.id)throw new Error(`Function ${f.name} did not return an ID`);let A=i.getOptions().tracer??M.tracer;return A?A.startActiveSpan(`Tool: ${f.name}`,async I=>{try{I?.setAttributes?.({"tool.name":f.name,"tool.mode":"native","function.id":f.id,"session.id":o??""});let b=await c.execute(f,{sessionId:o,ai:i,functionResultFormatter:p,traceId:I?.spanContext?.().traceId??r});if(m.add(f.name.toLowerCase()),a?I.addEvent("gen_ai.tool.message",{name:f.name}):I.addEvent("gen_ai.tool.message",{name:f.name,args:f.args,result:b??""}),s){let y={name:f.name};a||(y.args=f.args,y.result=b??""),s.addEvent("function.call",y)}return{result:b??"",role:"function",functionId:f.id,index:l}}catch(b){if(I?.recordException?.(b),b instanceof Xe){let y=b.getFixingInstructions(),R={name:f.name,message:b.toString()};return a||(R.args=f.args,R.fixing_instructions=y),I?.addEvent?.("function.error",R),d&&on(b,l,y,u),{functionId:f.id,isError:!0,index:l,result:y,role:"function"}}throw b}finally{I?.end?.()}}):c.execute(f,{sessionId:o,ai:i,functionResultFormatter:p,traceId:r}).then(I=>{if(m.add(f.name.toLowerCase()),s){let b={name:f.name};a||(b.args=f.args,b.result=I??""),s.addEvent("function.call",b)}return{result:I??"",role:"function",functionId:f.id,index:l}}).catch(I=>{if(!(I instanceof Xe))throw I;let b=I.getFixingInstructions();if(s){let y={name:f.name,message:I.toString()};a||(y.args=f.args,y.fixing_instructions=b),s.addEvent("function.error",y)}return d&&on(I,l,b,u),{functionId:f.id,isError:!0,index:l,result:b,role:"function"}})}),x=(await Promise.all(g)).filter(f=>f!==void 0);if(n.addFunctionResults(x,o),d){let f=x.filter(A=>!A.isError);f.length>0&&Ko(f,u)}return x.some(f=>f.isError)&&n.addTag("error",o),m};function ro(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(r=>({id:r.id,name:r.function.name,args:r.function.params}))}function Qr(i,e,t,n){let o=e;return n?.functionCallMode==="prompt"?{functions:[],functionCall:void 0}:!t&&(o==="required"||typeof o=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:o}:{functions:[],functionCall:o}}import le from"dayjs";import Ri from"dayjs/plugin/customParseFormat.js";import Ci from"dayjs/plugin/timezone.js";import wi from"dayjs/plugin/utc.js";le.extend(wi);le.extend(Ci);le.extend(Ri);function Yr(i,e,t=!1){try{return Si(e)}catch(n){if(i.isOptional&&!t)return;let o=n.message;throw new G({fields:[i],message:o,value:e})}}function Si(i){if(!le(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return le.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Xr(i,e,t=!1){try{return vi(e)}catch(n){if(i.isOptional&&!t)return;let o=n.message;throw new G({fields:[i],message:o,value:e})}}function vi(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,o]=t;if(!n||!o)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 r=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=le.tz(n,r,o);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 ${o}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Zr=i=>le(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Lc=new $,$t=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(p,u)=>{switch(p){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";default:return!1}},o=p=>!(!p||typeof p!="object"||!("mimeType"in p)||!("data"in p));if(i.type?.name==="image"){let p;if(Array.isArray(e)){for(let u of e)if(!o(u)){p="object ({ mimeType: string; data: string })";break}}else o(e)||(p="object ({ mimeType: string; data: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let r=p=>!(!p||typeof p!="object"||!("data"in p));if(i.type?.name==="audio"){let p;if(Array.isArray(e)){for(let u of e)if(!r(u)){p="object ({ data: string; format?: string })";break}}else r(e)||(p="object ({ data: string; format?: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let s=p=>{if(!p||typeof p!="object"||!("mimeType"in p))return!1;let u="data"in p,d="fileUri"in p;return!(!u&&!d||u&&d)};if(i.type?.name==="file"){let p;if(Array.isArray(e)){for(let u of e)if(!s(u)){p="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(p="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let a=p=>typeof p=="string"?!0:!(!p||typeof p!="object"||!("url"in p));if(i.type?.name==="url"){let p;if(Array.isArray(e)){for(let u of e)if(!a(u)){p="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(p="string or object ({ url: string; title?: string; description?: string })");if(p)throw new Error(`Validation failed: Expected '${i.name}' to be type '${p}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let p of e)if(!n(t.name,p)){l=!1;break}}else l=n(t.name,e);if(!l){let p=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${p}' (${JSON.stringify(e)})`)}};function Ze(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let o=e[n];if(o){let r=o.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};r.promptTokens+=t?.tokens?.promptTokens??0,r.completionTokens+=t?.tokens?.completionTokens??0,r.totalTokens+=t?.tokens?.totalTokens??0,o.tokens=r;let s=o.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(p=>p.url));for(let p of a)p?.url&&!l.has(p.url)&&(s.push(p),l.add(p.url));o.citations=s}}}return Object.values(e)}var es=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
190
+ `),o=[];for(let r of n){let s=r.trim();if(s){if(s[0]&&e.has(s[0]))o.push(s.slice(1).trim());else if(t.test(s))o.push(s.replace(t,"").trim());else if(o.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(o.length===0)throw new Error("Could not parse markdown list: no valid list items found");return o};function io(i,e){let{index:t,delta:n,version:o}=e,r=i.find(s=>s.index===t)?.delta;if(!r)return i.push({index:t,delta:n,version:o}),i;for(let s of Object.keys(n)){let a=r[s],l=n[s];a===void 0&&Array.isArray(l)?r[s]=[...l]:Array.isArray(a)&&Array.isArray(l)?r[s]=[...a,...l]:(a===void 0||typeof a=="string")&&typeof l=="string"?r[s]=`${a??""}${l}`:r[s]=l}return i}var so=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)}},Oi=new so(500);function ao(i,e,t=0,n=Oi){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let o=i.indexOf(e,t);if(o!==-1)return o;let r=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,r);let s=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}var os=(i,e,t,n=!1)=>{let o={extractedFields:[],streamedIndex:{},s:-1};lo(i,e,o,t,{strictMode:n}),po(i,e,o,t,n);for(let r of i.getOutputFields())r.isInternal&&delete e[r.name]},Mi=(i,e,t)=>{let n=[];for(let o of t)o&&!o.isOptional&&e[o.name]===void 0&&n.push(o);if(n.length>0)throw new G({message:`Required ${n.length===1?"field":"fields"} not found`,fields:n})},lo=(i,e,t,n,{strictMode:o,skipEarlyFail:r}={})=>{let s=i.getOutputFields(),a;for(let[l,p]of s.entries()){if(l===t.currFieldIndex&&!t.inAssumedField||p.name in e&&!(l===t.currFieldIndex&&t.inAssumedField))continue;let d=`${(t.extractedFields.length===0?"":`
191
+ `)+p.title}:`,c=ao(n,d,t.s),m=d.length;switch(c){case-1:if(r)continue;if(!o&&s.length===1&&t.currField===void 0){t.inAssumedField=!0,a=p,m=0,c=0;break}if(t.currField===void 0&&t.extractedFields.length===0){if(o&&!p.isOptional)throw new G({message:"Expected (Required) field not found",fields:[p]});if(!o){let g=!1;for(let h=l;h<s.length;h++){let x=s[h];if(!x)continue;let f=`${(t.extractedFields.length===0?"":`
192
+ `)+x.title}:`;if(ao(n,f,t.s)>=0){g=!0;break}}if(!g){t.inAssumedField=!0,a=p,m=0,c=0;break}}}a=p.isOptional?void 0:p;continue;case-2:return!0;case-3:return!0;case-4:return t.inBlock=!0,!0}if(a&&a.name!==p.name)throw new G({message:"Expected (Required) field not found",fields:[a]});if(t.currField!==void 0&&t.inAssumedField){let g=n.substring(0,c).trim();if(g&&t.currField.name===p.name){let h=et(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}else if(g){let h=et(t.currField,g);h!==void 0&&(e[t.currField.name]=h)}t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0}if(t.currField){let g=n.substring(t.s,c).trim(),h=et(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:c}):t.prevFields=[{field:t.currField,s:t.s,e:c}]}t.s=c+m,t.currField=p,t.currFieldIndex=l,t.extractedFields.includes(p)||t.extractedFields.push(p),t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},po=(i,e,t,n,o=!1)=>{if(t.currField){let r=n.substring(t.s).trim(),s=et(t.currField,r);s!==void 0&&(e[t.currField.name]=s)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let a=i.getOutputFields().find(l=>!l.isOptional);if(a)throw new G({message:"Expected field not found",fields:[a]})}ki(i,e,n),Mi(t,e,i.getOutputFields())},ki=(i,e,t)=>{let n=i.getOutputFields();for(let o of n){if(!o.isOptional||o.name in e)continue;let r=`${o.title}:`,s=t.indexOf(r);if(s===-1)continue;let a=s+r.length,l=t.length;for(let u of n){if(u.name===o.name)continue;let d=`${u.title}:`,c=t.indexOf(d,a);c!==-1&&c<l&&(l=c)}let p=t.substring(a,l).trim();if(p)try{let u=et(o,p);u!==void 0&&(e[o.name]=u)}catch{}}},ts=(i,e,t=!1)=>{switch(i.type?.name){case"code":return rs(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 Yr(i,e,t);case"datetime":return Xr(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*ns(i,e,t,n,o,r){let{name:s,isInternal:a}=e,{isArray:l,name:p}=e.type??{};if(a||l||p&&p!=="string"&&p!=="code")return;let u=o.streamedIndex[s]??0,d=u===0,c=i.substring(t+u,n);if(c.length===0)return;let m=c.replace(/\s+$/,"");o.currField?.type?.name==="code"&&(m=m.replace(/\s*```\s*$/,""));let g=d?m.trimStart():m;o.currField?.type?.name==="code"&&(g=g.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),g.length>0&&(yield{index:r,delta:{[s]:g}},o.streamedIndex[s]=u+m.length)}function*uo(i,e,t,n,o){for(let s of n.prevFields??[]){let{field:a,s:l,e:p}=s;yield*ns(e,a,l,p,n,o)}if(n.prevFields=void 0,!n.currField||n.currField.isInternal)return;yield*ns(e,n.currField,n.s,e.length,n,o);let r=i.getOutputFields();for(let s of Object.keys(t)){let a=r.find(p=>p.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let p=n.streamedIndex?.[s]??0,u=l.slice(p);u&&u.length>0&&(yield{index:o,delta:{[s]:u}},n.streamedIndex[s]=p+u.length);continue}n.streamedIndex[s]||(yield{index:o,delta:{[s]:l}},n.streamedIndex[s]=1)}}function et(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw new G({message:"Required field is missing",fields:[i],value:e})}let t;if(i.type?.name==="json")try{let n=rs(e);return t=JSON.parse(n),t}catch(n){throw new G({message:`Invalid JSON: ${n.message}`,fields:[i],value:e})}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=es(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw new G({message:`Invalid Array: ${n.message}`,fields:[i],value:e})}try{if(Array.isArray(t)){for(let[n,o]of t.entries())if(o!==void 0){let r=typeof o=="string"?o.trim():o;t[n]=ts(i,r,!0)}}else t=ts(i,e)}catch(n){throw new G({message:n.message,fields:[i],value:e})}if(!(typeof t=="string"&&t===""))return t}var rs=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function co(i,e,t,n){for(let o of i){if(e[o.field.name]===void 0)continue;let r=o.process,s=await r(e[o.field.name],{sessionId:n,values:e,done:!0});ss(o.field,t,s,n)}}async function mo(i,e,t,n,o,r,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 p=a.process,u=await p(l,{sessionId:r,values:o,done:s});ss(t.currField,n,u,r)}}var ss=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let o=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),r=Ei(i,o);e.addRequest([{role:"user",content:[{type:"text",text:r}]}],n),e.addTag("processor",n)};function Ei(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*is({res:i,usage:e,states:t,debug:n,...o}){let r=(o.ai.getFeatures().functionCot??!1)&&o.functions!==void 0&&o.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:p,value:u}=await l.read();if(p)break;let d=u;d.modelUsage&&(s=d.modelUsage);for(let c of d.results){if(Array.isArray(c.citations))for(let g of c.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!c.content||c.content==="")&&(!c.thought||c.thought==="")&&(!c.functionCalls||c.functionCalls.length===0))continue;let m=t.find(g=>g.index===c.index);if(!m)throw new Error(`No state found for result (index: ${c.index})`);yield*Pi({...o,result:c,skipEarlyFail:r,state:m,debug:n})}}}finally{l.releaseLock()}for(let p of t)yield*Fi({...o,state:p,debug:n});if(s){if(a.length){let p=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());s.citations=p}if(e.push(s),n&&o.logger){let p=structuredClone(s);delete p.citations,o.logger({name:"ChatResponseUsage",value:p}),s.citations&&s.citations.length>0&&o.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*Pi({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:o,state:r,signature:s,streamingFieldProcessors:a,thoughtFieldName:l,streamingAsserts:p,asserts:u}){if(i.functionCalls&&i.functionCalls.length>0)mt(r.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:r.functionCalls,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){if(i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[l]:i.thought}}),r.content+=i.content,e.updateResult({name:i.name,content:r.content,delta:i.content,index:i.index},t),lo(s,r.values,r.xstate,r.content,{strictMode:n,skipEarlyFail:o}))return;p.length!==0&&await Xn(p,r.xstate,r.content),a.length!==0&&await mo(a,r.content,r.xstate,e,r.values,t),yield*uo(s,r.content,r.values,r.xstate,i.index),await Ft(u,r.values)}else i.thought&&i.thought.length>0&&(r.values[l]=(r.values[l]??"")+i.thought,yield{index:i.index,delta:{[l]:i.thought}});if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
193
+ Content: ${r.content}`)}async function*Fi({state:i,signature:e,ai:t,model:n,functions:o,mem:r,sessionId:s,traceId:a,span:l,strictMode:p,excludeContentFromTrace:u,streamingAsserts:d,asserts:c,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,logger:x,debug:f}){let A=ro(t,i.functionCalls,i.values,n);if(A){if(!o)throw new Error("Functions are not defined");let I=await oo({ai:t,functionList:o,functionCalls:A,mem:r,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:x,debug:f});i.functionsExecuted=new Set([...i.functionsExecuted,...I]),i.functionCalls=[]}else po(e,i.values,i.xstate,i.content,p),await Xn(d,i.xstate,i.content,!0),await Ft(c,i.values),m.length&&await co(m,i.values,r,s),g.length!==0&&await mo(g,i.content,i.xstate,r,i.values,s,!0),yield*uo(e,i.content,i.values,i.xstate,i.index)}async function*as({ai:i,res:e,mem:t,sessionId:n,traceId:o,functions:r,span:s,strictMode:a,states:l,usage:p,excludeContentFromTrace:u,asserts:d,fieldProcessors:c,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:x,debug:f}){let A=e.results??[];t.addResponse(A,n);let I=[];for(let T of A)if(Array.isArray(T?.citations))for(let w of T.citations)w?.url&&I.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let T of A){let w=l[T.index];if(!w)throw new Error(`No state found for result (index: ${T.index})`);if(e.modelUsage){let P=Array.from(new Map(I.filter(F=>F.url).map(F=>[F.url,F])).values()),k={...e.modelUsage,...P.length?{citations:P}:{}};if(p.push(k),f&&x){let F=structuredClone(k);delete F.citations,x({name:"ChatResponseUsage",value:F}),k.citations&&k.citations.length>0&&x({name:"ChatResponseCitations",value:k.citations})}}if(T.functionCalls?.length){let P=ro(i,T.functionCalls,w.values);if(P){if(!r)throw new Error("Functions are not defined");let k=await oo({ai:i,functionList:r,functionCalls:P,mem:t,sessionId:n,traceId:o,span:s,excludeContentFromTrace:u,index:T.index,functionResultFormatter:h,logger:x,debug:f});w.functionsExecuted=new Set([...w.functionsExecuted,...k])}}else T.content&&(T.thought&&T.thought.length>0&&(w.values[m]=T.thought),os(g,w.values,T.content,a),await Ft(d,w.values),c.length&&await co(c,w.values,t,n));if(T.finishReason==="length")throw new Error(`Max tokens reached before completion
194
+ Content: ${T.content}`)}let b=l.map(T=>T.values);for(let T of b)for(let w of g.getOutputFields())w.isInternal&&delete T[w.name];let y=g.getOutputFields(),R=b.map((T,w)=>{let P={};for(let k of y)k.isInternal||(P[k.name]=T[k.name]);return T[m]!==void 0&&(P[m]=T[m]),{index:w,delta:P}});for(let T of R)yield T}function ls(i,e,t,n){let o=i.getLast(n);if(!o)return!0;for(let[r,s]of t.entries()){let a=e&&s.functionsExecuted.has(e);if(!o.chat[r])throw new Error(`No chat message found for result (index: ${r})`);let p=o.role==="function",u=o.tags?o.tags.some(d=>d==="processor"):!1;if(p&&e&&a||!(p||u))return!1}return!0}var tt=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 S=class extends Error{constructor(t,n,o,r){super(t);this.position=n;this.context=o;this.suggestion=r;this.name="SignatureValidationError"}},go=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new S("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 S("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 S('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 o=this.input.slice(this.position);throw new S(`Unexpected content after signature: "${o}"`,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 S)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new S(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let o of e.inputs){if(t.has(o.name))throw new S(`Duplicate input field name: "${o.name}"`,0,"","Each field name must be unique within the signature");t.add(o.name)}let n=new Set;for(let o of e.outputs){if(n.has(o.name))throw new S(`Duplicate output field name: "${o.name}"`,0,"","Each field name must be unique within the signature");n.add(o.name)}for(let o of e.outputs)if(t.has(o.name))throw new S(`Field name "${o.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 S("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new S("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),o=this.input.slice(this.position,t),r=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${o}"`,` ${r}`].join(`
195
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new S(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(o){throw o instanceof S?o:new S(`Invalid first ${t} field: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new S(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(o){throw o instanceof S?o:new S(`Invalid ${t} field after comma: ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new S(`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 S(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let r=this.parseTypeNotClass(),s=this.match("[]");n={name:r,isArray:s}}catch(r){throw r instanceof S?r:new S(`Input field "${e}": ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let o;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new S(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(p=>p.trim()).filter(p=>p.length>0);if(l.length===0)throw new S(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');o={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(o={name:s,isArray:a},s==="image"&&a)throw new S(`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 S(`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 S(`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 S(`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 S?s:new S(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:o,isOptional:t,isInternal:n}}validateFieldName(e,t){if(M.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 S(`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]*$/,o=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!o.test(e))throw new S(`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 S(`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 S(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",o=this.suggestType(n),r=`Invalid type "${n||"empty"}"`,s=o?`. Did you mean "${o}"?`:"",a=`${r}${s}`;throw new S(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 S("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 S(`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 S(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",o=!1,r=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,o)n+=a,o=!1;else if(a==="\\")o=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(r,Math.min(this.position,r+20));throw new S(`Unterminated string starting at position ${r}`,r,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 S(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function ps(i){return new go(i).parse()}var Bt=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let o={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.inputFields.unshift(o):this.inputFields.push(o),this}output(e,t,n=!1){let o={name:e,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional,isInternal:t.isInternal};return n?this.outputFields.unshift(o):this.outputFields.push(o),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new L(e)}},U=class i{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new i({...this,isOptional:!0})}array(){return new i({...this,isArray:!0})}internal(){return new i({...this,isInternal:!0})}},nt=Object.assign(()=>new Bt,{string:i=>new U({type:"string",isArray:!1,description:i}),number:i=>new U({type:"number",isArray:!1,description:i}),boolean:i=>new U({type:"boolean",isArray:!1,description:i}),json:i=>new U({type:"json",isArray:!1,description:i}),datetime:i=>new U({type:"datetime",isArray:!1,description:i}),date:i=>new U({type:"date",isArray:!1,description:i}),class:(i,e)=>new U({type:"class",isArray:!1,options:i,description:e}),image:i=>new U({type:"image",isArray:!1,description:i}),audio:i=>new U({type:"audio",isArray:!1,description:i}),file:i=>new U({type:"file",isArray:!1,description:i}),url:i=>new U({type:"url",isArray:!1,description:i}),code:(i,e)=>new U({type:"code",isArray:!1,description:e||i}),array:i=>({...i,isArray:!0}),optional:i=>({...i,isOptional:!0}),internal:i=>({...i,isInternal:!0}),legacyArray:i=>({...i,isArray:!0}),legacyOptional:i=>({...i,isOptional:!0}),legacyInternal:i=>({...i,isInternal:!0})});function Ut(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var C=class extends Error{constructor(t,n,o){super(t);this.fieldName=n;this.suggestion=o;this.name="AxSignatureValidationError"}},L=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=ps(e)}catch(n){if(n instanceof Error){let o="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new C(`Invalid Signature: ${n.message}`,void 0,o)}throw new C(`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);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new C("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 C("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 C?t:new C(`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 C("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 C("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 C("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 C("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);ne(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new C(`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 C(`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 C?t:new C(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ne(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new C(`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 C(`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 C?t:new C(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new C("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ne(o,"input"),o});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof C?t:new C(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new C("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return ne(o,"output"),o});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof C?t:new C(`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,...Ut(t)}),n};prependInputField=(e,t)=>{let n=new i(this),o={name:e,...Ut(t)},r=n.parseField(o);ne(r,"input");for(let s of n.inputFields)if(s.name===r.name)throw new C(`Duplicate input field name: "${r.name}"`,r.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===r.name)throw new C(`Field name "${r.name}" appears in both inputs and outputs`,r.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(r),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Ut(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),o={name:e,...Ut(t)},r=n.parseField(o);ne(r,"output");for(let s of n.outputFields)if(s.name===r.name)throw new C(`Duplicate output field name: "${r.name}"`,r.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===r.name)throw new C(`Field name "${r.name}" appears in both inputs and outputs`,r.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(r),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let o of this.inputFields){let r=o.type?o.type.name:"string";o.type?.isArray?e[o.name]={description:o.description,type:"array",items:{type:r,description:o.description}}:e[o.name]={description:o.description,type:r},o.isOptional||t.push(o.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ne(e,"input")}),this.getOutputFields().forEach(e=>{ne(e,"output")}),this.sigHash=pt("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=cs(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof C?e:new C(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ne(e,"input")}),this.getOutputFields().forEach(e=>{ne(e,"output")}),this.validateSignatureConsistency(),this.sigHash=pt("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=cs(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof C?e:new C(`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 C(`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 C(`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 C(`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 C("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new C("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;injectToolFields(e){let t=new i(this);for(let n of e)if(n.parameters?.properties&&Object.keys(n.parameters.properties).length>0){let o=this.generateToolParameterFields(n);for(let r of o)t.outputFields.some(a=>a.name===r.name)||t.addOutputField(r)}else{let o=this.sanitizeFieldName(n.name),r=this.inferToolFieldType(n.parameters);t.outputFields.some(a=>a.name===o)||t.addOutputField({name:o,title:this.formatTitle(n.name),type:r,description:n.description||`Parameters for ${n.name}`,isOptional:!0})}return t}generateToolParameterFields(e){let t=[];if(!e.parameters||!e.parameters.properties)return t;let n=e.parameters.properties,o=e.parameters.required||[],r=(s,a,l)=>{for(let[p,u]of Object.entries(s)){let d=a?`${a}.${p}`:p,c=`${e.name}.${d}`;if(u.type==="object"&&u.properties)r(u.properties,d,u.required||[]);else{let m=this.inferParameterType(u);t.push({name:this.sanitizeFieldName(c),title:this.formatParameterTitle(e.name,d),type:m,description:u.description||`${p} parameter for ${e.name}`,isOptional:!0})}}};return r(n,"",o),t}inferParameterType(e){switch(e.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 t=e.items;if(t?.type)switch(t.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}}}formatParameterTitle(e,t){return`${e} ${t.replace(/\./g," ")}`}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}formatTitle(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}inferToolFieldType(e){return!e||!e.properties||Object.keys(e.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function us(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 cs(i,e,t){let n=i?`"${i}" `:"",o=e.map(us).join(", "),r=t.map(us).join(", ");return`${n}${o} -> ${r}`}function _i(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ne(i,e){if(!i.name||i.name.length===0)throw new C("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!_i(i.name))throw new C(`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(M.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 C(`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 C(`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 C(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Di(i,e)}function Di(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new C(`${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 C("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 C("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let o of t.options){if(!o||o.trim().length===0)throw new C("Empty class option found",i.name,"All class options must be non-empty strings");let r=o.trim();if(r.includes(",")||r.includes("|"))throw new C(`Invalid class option "${r}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(o=>o.trim().toLowerCase())).size!==t.options.length)throw new C("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new C("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 C("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields")}var pe=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new L(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 tt,this.key={id:this.signature.hash()}}getSignature(){return new L(this.signature)}setSignature(e){this.signature=new L(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let o=this.signature,r=[...o.getInputFields(),...o.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of r){let p=s[l.name];p!==void 0&&($t(l,p),a[l.name]=p)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return Ze(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(o=>o.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(o=>o.programId===this.key.id).map(o=>o.traces).flat();for(let o of Array.from(this.children))o?.setDemos(e)}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 Li=`
196
196
  ## Function Call Instructions
197
197
  - Complete the task, using the functions defined earlier in this prompt.
198
198
  - Output fields should only be generated after all functions have been called.
199
- - Use the function results to generate the output fields.`,$i=`
199
+ - Use the function results to generate the output fields.`,Ni=`
200
200
  ## Strict Output Formatting Rules
201
201
  - Output must strictly follow the defined plain-text \`field name: value\` field format.
202
202
  - Output field, values must strictly adhere to the specified output field formatting rules.
203
203
  - No formatting rules should override these **Strict Output Formatting Rules**
204
204
  - Do not add any text before or after the output fields, just the field name and value.
205
- - Do not use code blocks.`,fe=class{sig;fieldTemplates;task;thoughtFieldName;functions;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions;let o=[],r=ds(this.sig.getInputFields()),s=ds(this.sig.getOutputFields());o.push(`You will be provided with the following fields: ${r}. Your task is to generate new fields: ${s}.`);let l=this.functions?.map(d=>"toFunction"in d?d.toFunction():d)?.flat()?.map(d=>`- \`${d.name}\`: ${qt(d.description)}`).join(`
205
+ - Do not use code blocks.`,fe=class{sig;fieldTemplates;task;thoughtFieldName;functions;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions;let o=[],r=ds(this.sig.getInputFields()),s=ds(this.sig.getOutputFields());o.push(`You will be provided with the following fields: ${r}. Your task is to generate new fields: ${s}.`);let l=this.functions?.map(c=>"toFunction"in c?c.toFunction():c)?.flat()?.map(c=>`- \`${c.name}\`: ${qt(c.description)}`).join(`
206
206
  `);l&&l.length>0&&o.push(`## Available Functions
207
207
  ${l}`);let p=Gi(this.sig.getInputFields());o.push(`## Input Fields
208
- ${p}`);let u=Ui(this.sig.getOutputFields());o.push(`## Output Fields
209
- ${u}`),l&&l.length>0&&o.push(Ni.trim()),o.push($i.trim());let c=this.sig.getDescription();if(c){let d=qt(c);o.push(d)}this.task={type:"text",text:o.join(`
208
+ ${p}`);let u=$i(this.sig.getOutputFields());o.push(`## Output Fields
209
+ ${u}`),l&&l.length>0&&o.push(Li.trim()),o.push(Ni.trim());let d=this.sig.getDescription();if(d){let c=qt(d);o.push(c)}this.task={type:"text",text:o.join(`
210
210
 
211
211
  `)}}renderSingleValueUserContent=(e,t,n,o)=>{let r=this.renderInputFields(e),a=(o?r:[...t,...n,...r]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
212
212
  `):a.reduce(ms(`
213
213
  `),[])};render=(e,{examples:t,demos:n})=>{let o=t?[{type:"text",text:`
214
214
 
215
215
  ## Examples
216
- `},...this.renderExamples(t)]:[],r=n?this.renderDemos(n):[],s=o.every(d=>d.type==="text"),a=r.every(d=>d.type==="text"),l=s&&a,p=this.task.text;if(l){let d=[{type:"text",text:p},...o,...r];d.reduce(ms(""),[]),d?.[0]&&(p=d[0].text)}let u={role:"system",content:p};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let h of m){let f;if(g?(f=this.renderSingleValueUserContent(h.values,o,r,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 c=this.renderSingleValueUserContent(e,o,r,l);return[u,{role:"user",content:c}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((r,s)=>{let a=s.title;return r[a]||(r[a]=[]),r[a].push(s),r},{});return Object.entries(n).map(([r,s])=>{if(s.length===1){let a=s[0];return{title:r,name:a.name,description:a.description}}if(s.length>1){let a=s.map(l=>`- ${l.description}`).join(`
216
+ `},...this.renderExamples(t)]:[],r=n?this.renderDemos(n):[],s=o.every(c=>c.type==="text"),a=r.every(c=>c.type==="text"),l=s&&a,p=this.task.text;if(l){let c=[{type:"text",text:p},...o,...r];c.reduce(ms(""),[]),c?.[0]&&(p=c[0].text)}let u={role:"system",content:p};if(Array.isArray(e)){let c=[],m=e,g=!0;for(let h of m){let x;if(g?(x=this.renderSingleValueUserContent(h.values,o,r,l),g=!1):x=this.renderSingleValueUserContent(h.values,[],[],!1),h.role==="user"){c.push({role:"user",content:x});continue}if(h.role!=="assistant")throw new Error("Invalid message role");if(typeof x!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");c.push({role:"assistant",content:x})}return[u,...c]}let d=this.renderSingleValueUserContent(e,o,r,l);return[u,{role:"user",content:d}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((r,s)=>{let a=s.title;return r[a]||(r[a]=[]),r[a].push(s),r},{});return Object.entries(n).map(([r,s])=>{if(s.length===1){let a=s[0];return{title:r,name:a.name,description:a.description}}if(s.length>1){let a=s.map(l=>`- ${l.description}`).join(`
217
217
  `);return{title:r,name:s[0].name,description:a}}}).filter(Boolean).forEach(r=>{let s=this.fieldTemplates?.[r.name]??this.defaultRenderInField;t.push(...s(r,r.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0};for(let[o,r]of e.entries()){let s=this.sig.getInputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!0})).filter(p=>p!==void 0).flat(),a=this.sig.getOutputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!1})).filter(p=>p!==void 0).flat(),l=[...s,...a];o>0&&l.length>0&&l[0]?.type==="text"&&t.push({type:"text",text:`---
218
218
 
219
219
  `}),l.forEach(p=>{"text"in p&&(p.text=`${p.text}
220
220
  `),t.push(p)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),o=this.sig.getOutputFields(),r={isExample:!0};for(let s of e){let a=n.map(u=>this.renderInField(u,s,{...r,isInputField:!0})).filter(u=>u!==void 0).flat(),l=o.map(u=>this.renderInField(u,s,{...r,isInputField:!1})).filter(u=>u!==void 0).flat();[...a,...l].slice(0,-1).forEach(u=>{"text"in u&&(u.text=`${u.text}
221
221
  `),t.push(u)})}return t};renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
222
- `}),t};renderInField=(e,t,n)=>{let o=t[e.name];if(qi(e,o,n))return;e.type&&Gt(e,o);let r=Bi(e,o);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,r)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let o=s=>{if(!s)throw new Error("Image field value is required.");if(typeof s!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in s))throw new Error("Image field must have mimeType");if(!("data"in s))throw new Error("Image field must have data");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let s=o(t);r.push({type:"image",mimeType:s.mimeType,image:s.data})}return r}if(e.type?.name==="audio"){let o=s=>{if(!s)throw new Error("Audio field value is required.");if(typeof s!="object")throw new Error("Audio field value must be an object.");if(!("data"in s))throw new Error("Audio field must have data");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let s=o(t);r.push({type:"audio",format:s.format??"wav",data:s.data})}return r}if(e.type?.name==="file"){let o=s=>{if(!s)throw new Error("File field value is required.");if(typeof s!="object")throw new Error("File field value must be an object.");if(!("mimeType"in s))throw new Error("File field must have mimeType");let a="data"in s,l="fileUri"in s;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let s=o(t);r.push("fileUri"in s?{type:"file",mimeType:s.mimeType,fileUri:s.fileUri}:{type:"file",mimeType:s.mimeType,data:s.data})}return r}if(e.type?.name==="url"){let o=s=>{if(!s)throw new Error("URL field value is required.");if(typeof s=="string")return{url:s};if(typeof s!="object")throw new Error("URL field value must be a string or object.");if(!("url"in s))throw new Error("URL field must have url property");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let s=o(t);r.push({type:"url",url:s.url,...s.title?{title:s.title}:{},...s.description?{description:s.description}:{}})}return r}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
222
+ `}),t};renderInField=(e,t,n)=>{let o=t[e.name];if(Bi(e,o,n))return;e.type&&$t(e,o);let r=Ui(e,o);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,r)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let o=s=>{if(!s)throw new Error("Image field value is required.");if(typeof s!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in s))throw new Error("Image field must have mimeType");if(!("data"in s))throw new Error("Image field must have data");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let s=o(t);r.push({type:"image",mimeType:s.mimeType,image:s.data})}return r}if(e.type?.name==="audio"){let o=s=>{if(!s)throw new Error("Audio field value is required.");if(typeof s!="object")throw new Error("Audio field value must be an object.");if(!("data"in s))throw new Error("Audio field must have data");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let s=o(t);r.push({type:"audio",format:s.format??"wav",data:s.data})}return r}if(e.type?.name==="file"){let o=s=>{if(!s)throw new Error("File field value is required.");if(typeof s!="object")throw new Error("File field value must be an object.");if(!("mimeType"in s))throw new Error("File field must have mimeType");let a="data"in s,l="fileUri"in s;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let s=o(t);r.push("fileUri"in s?{type:"file",mimeType:s.mimeType,fileUri:s.fileUri}:{type:"file",mimeType:s.mimeType,data:s.data})}return r}if(e.type?.name==="url"){let o=s=>{if(!s)throw new Error("URL field value is required.");if(typeof s=="string")return{url:s};if(typeof s!="object")throw new Error("URL field value must be a string or object.");if(!("url"in s))throw new Error("URL field must have url property");return s},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");r=r.concat(t.map(s=>{let a=o(s);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let s=o(t);r.push({type:"url",url:s.url,...s.title?{title:s.title}:{},...s.description?{description:s.description}:{}})}return r}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
223
223
  `),n.push(t.map(o=>`- ${o}`).join(`
224
224
  `))):n.push(t),[{type:"text",text:n.join("")}]}},ds=i=>i.map(e=>`\`${e.title}\``).join(", "),Gi=i=>i.map(t=>{let n=t.title,o=t.type?.name?gs(t.type):"string",r=t.isOptional?`This optional ${o} field may be omitted`:`A ${o} field`,s=t.description?` ${qt(t.description)}`:"";return`${n}: (${r})${s}`.trim()}).join(`
225
- `),Ui=i=>i.map(t=>{let n=t.title,o=t.type?.name?gs(t.type):"string",r=t.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:qt(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${r})${s}`.trim()}).join(`
226
- `),Bi=(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?Zr(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)},gs=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)";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function ms(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 qi=(i,e,t)=>{if(typeof e=="boolean")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 qt(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function zi(i,e){let t=i.history(0,e),n=t.some(r=>r.role==="function");return t.some(r=>r.role==="assistant"&&"functionCalls"in r&&Array.isArray(r.functionCalls)&&r.functionCalls.length>0)&&n}function ji(i,e){let t=i.history(0,e),n=[],o=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),r=t.filter(s=>s.role==="function");for(let s of o)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=r.find(p=>"functionId"in p&&p.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function zt(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let o=e.resultPicker;if((t?zi(t,n):!1)&&t){let l=ji(t,n),p=await o({type:"function",results:l});if(p<0||p>=l.length)throw new Error(`Result picker returned invalid index: ${p}. Must be between 0 and ${l.length-1}`);return p}let s=i.map((l,p)=>({index:p,sample:l.delta})),a=await o({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 hs(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let o=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await zt(o,t,i,e)}import{trace as Hi}from"@opentelemetry/api";var ot=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}async route(e,t){let n={},o={},r=[];for(let[a,l]of Object.entries(e)){let p=this.tools.get(this.normalizeToolName(a));if(p&&l!==void 0&&l!==null)try{let u=await this.executeTool(p,l,t);n[a]=u,r.push(p.name)}catch{o[a]=l}else o[a]=l}let s={...o,...n};return{toolResults:n,remainingFields:s}}async executeTool(e,t,n){if(!e.func)throw new Error(`Tool ${e.name} has no handler function`);let o=typeof t=="object"&&t!==null?t:{},r=M.tracer??Hi.getTracer("ax");if(!r){let s=e.func;return await s(o,{sessionId:n?.sessionId,traceId:n?.traceId})}return await r.startActiveSpan(`Tool: ${e.name}`,async s=>{try{s.setAttributes?.({"tool.name":e.name,"tool.mode":"prompt"});let a=e.func,l=await a(o,{sessionId:n?.sessionId,traceId:s.spanContext().traceId});return s.addEvent("gen_ai.tool.message",{name:e.name,args:JSON.stringify(o),result:typeof l=="string"?l:JSON.stringify(l??"")}),l}catch(a){throw s.recordException(a),s.addEvent("function.error",{name:e.name,message:a.toString()}),a}finally{s.end()}})}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}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(/^_/,""))}};var jt=class{functionCallMode;tools;router;usePromptMode=!1;constructor(e){this.functionCallMode=e.functionCallMode??"auto",this.tools=e.functions??[],this.functionCallMode==="prompt"&&this.tools.length>0&&(this.usePromptMode=!0,this.router=new ot(this.tools))}setUsePromptMode(e){this.usePromptMode=e,e&&this.tools.length>0&&!this.router&&(this.router=new ot(this.tools))}getMode(){return this.functionCallMode}processSignature(e){return this.usePromptMode&&this.tools.length>0?e.injectToolFields(this.tools):e}async processResults(e,t){return this.usePromptMode&&this.router?(await this.router.route(e,t)).remainingFields:e}isPromptModeEnabled(){return this.usePromptMode}isNativeModeEnabled(){return!this.usePromptMode&&this.tools.length>0}getRouter(){return this.router}};var H=class extends pe{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??fe)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.usage=[],t?.functions&&(this.functions=no(t.functions),t?.functionCallMode&&(this.signatureToolCallingManager=new jt({functionCallMode:t.functionCallMode,functions:this.functions})))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Zn()}updateMeter(e){Zn(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let o=this.signature.getOutputFields().find(r=>r.name===e);if(!o)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let r=o.type?.name;if(!(!r||r==="string"||r==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:o,process:t})}else this.fieldProcessors.push({field:o,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:r,functionCall:s,stepIndex:a}){let{sessionId:l,model:p,rateLimiter:u,stream:c,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await hs(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}:{}},I=this.isDebug(e,n),A=a===0,b=this.getLogger(e,n);return await e.chat({chatPrompt:h,functions:r,functionCall:s,modelConfig:f,model:p},{sessionId:l,rateLimiter:u,stream:c,debug:I,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:o,abortSignal:n?.abortSignal,stepIndex:a,logger:b})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:o,span:r,traceContext:s,states:a}){let{sessionId:l,functions:p}=n??{},u=n?.functionCall??this.options?.functionCall,c=n?.strictMode??!1,d=n.model,m=this.usage,g=o===0,h=this.getLogger(e,n),{functions:f,functionCall:I}=Qr(p,u,g,n),A=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:f,functionCall:I,stepIndex:o});A instanceof ReadableStream?yield*is({ai:e,model:d,res:A,mem:t,sessionId:l,traceId:r?r.spanContext?.().traceId:void 0,functions:f,strictMode:c,span:r,states:a,usage:m,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter}):yield*as({ai:e,model:d,res:A,mem:t,sessionId:l,traceId:r?r.spanContext?.().traceId:void 0,functions:f,span:r,strictMode:c,states:a,usage:m,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter})}async*_forward2(e,t,n,o,r,s){let a=(o?.stopFunction??this.options?.stopFunction)?.toLowerCase(),l=o.maxRetries??this.options?.maxRetries??10,p=o.maxSteps??this.options?.maxSteps??10,u=o.mem??this.options?.mem??new Qe;if(this.signatureToolCallingManager?.getMode()==="auto"&&this.functions&&this.functions.length>0){let b=e.getFeatures(o.model).functions;this.signatureToolCallingManager.setUsePromptMode(!b)}let c;{let A=this.options?.promptTemplate??fe,b=this.signature;this.signatureToolCallingManager?.isPromptModeEnabled()&&(b=this.signatureToolCallingManager.processSignature(this.signature));let R={functions:o?.functions??this.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new A(b,R)}let d,m=performance.now();Array.isArray(t)?(xr(t),d=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):d=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let g=performance.now()-m,h=this.getMetricsInstruments();h&&Lt(h,"prompt_render",g,this.getSignatureName());let f=performance.now();u.addRequest(d,o.sessionId);let I=performance.now()-f;h&&Lt(h,"memory_update",I,this.getSignatureName());e:for(let A=0;A<p;A++){for(let R=0;R<l;R++)try{let y=this.forwardCore({options:o,ai:e,mem:u,stepIndex:A,span:r,traceContext:s,states:n});for await(let v of y)v!==void 0&&(yield{version:R,index:v.index,delta:v.delta});if(ls(u,a,n,o?.sessionId)){let v=this.getMetricsInstruments();v&&Dt(v,A+1,p,this.getSignatureName());continue e}let T=this.getMetricsInstruments();if(T){Dt(T,A+1,p,this.getSignatureName());let v=new Set;n.forEach(k=>{k.functionsExecuted.forEach(P=>v.add(P))}),v.size>0&&Br(T,!0,v.size,!0,!1,this.getSignatureName()),qr(T,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(y){let x,T=this.isDebug(e,o),v=this.getLogger(e,o),k=this.getMetricsInstruments(),P=this.getSignatureName(),U={error:y,errCount:R,logger:v,metricsInstruments:k,signatureName:P,span:r,debug:T};if(r?.recordException(y),y instanceof N)x=Kr(U),c=y;else if(y instanceof ae)x=Wr(U),c=y;else if(y instanceof E)Vr(U);else if(!(y instanceof Z))throw ho(y,e,this.signature);x&&(u.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(x)}],o.sessionId),u.addTag("error",o.sessionId))}let b=this.getMetricsInstruments();throw b&&to(b,l,!1,l,this.getSignatureName()),ho(new Error(`Unable to fix validation error: ${c?.toString()}`),e,this.signature)}throw h&&Dt(h,p,p,this.getSignatureName()),ho(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let o=performance.now(),r=this.createStates(n.sampleCount??1),s=performance.now()-o,a=this.getMetricsInstruments();a&&Lt(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,p=this.functions;if(n?.functions&&(p=no(n.functions,this.functions)),!l){yield*this._forward2(e,t,r,{...n,functions:p});return}let u=p?.map(I=>I.name).join(","),c={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:Wi.SERVER,attributes:c}),h=Ki.active(),f=Vi.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,r,{...n,functions:p},g,f),!this.excludeContentFromTrace){let I=r.map(b=>b.values),A=I.length===1?I[0]:I;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let o=performance.now(),r=this.getSignatureName(),s=n?.stream??!1,a=!1,l=0,p=!1;try{let u=this.getMetricsInstruments();u&&Hr(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,r);let c=this._forward1(e,t,n??{}),d=[],m=0,g=0;for await(let y of c)y.version!==m&&(d=[]),m=y.version,d=io(d,y),g++;l=m;let h=performance.now();p=!!n?.resultPicker;let f=await zt(d,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),I=performance.now()-h,b=d[f]?.delta??{};this.signatureToolCallingManager?.isPromptModeEnabled()&&(b=await this.signatureToolCallingManager.processResults(b,{sessionId:n?.sessionId}));let R=Array.isArray(t)?{}:t??{};if(this.trace={...R,...b},p&&this.isDebug(e,n)){let y=this.getLogger(e,n);Xo(d.length,f,I,y)}return a=!0,u&&(jr(u,d.length,p,p?I:void 0,r),zr(u,s,g,void 0,r)),b}catch(u){throw a=!1,u}finally{let u=performance.now()-o,c=this.getMetricsInstruments();c&&(Gr(c,u,a,r,e.getName(),n?.model?String(n.model):void 0),l>0&&to(c,l,a,n?.maxRetries??10,r))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),r=[],s=0;for await(let p of o)p.version!==s&&(r=[]),s=p.version,r=io(r,p);let a=await zt(r,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=r[a];l&&(yield{version:s,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??M.logger??e.getLogger()}},Ht=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function ho(i,e,t){let n=i instanceof Error?i:new Error(String(i)),o=e.getLastUsedChatModel(),r=e.getLastUsedModelConfig(),s={model:o,maxTokens:r?.maxTokens,streaming:r?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Ht("Generate failed",s,{cause:n})}var Ji=i=>i.replace(/^\W+|\W+$/g,""),Qi=(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 o=i.substring(0,t),r=i.substring(t+n[0].length);return[o,r]},Yi=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Xi=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}},Zi=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},ea=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},fo={trimNonAlphaNum:Ji,splitIntoTwo:Qi,dedup:Yi,extractIdAndText:Xi,extractIndexPrefixedText:Zi,batchArray:ea};var Ao=class extends H{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."
227
- query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:o}=await super.forward(e,t,n),r=o.map(a=>{let{id:l}=fo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let p=r[l];return p!==void 0?t.items[p]:void 0}).filter(a=>a!==void 0)}}};var xo=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 o={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(o.duplex="half");let r=await(this.fetch??fetch)(this.tikaUrl,o);if(!r.ok)throw new Error(`Failed to upload file: ${r.statusText}`);return await r.text()}catch(o){throw new Error(`Error converting file: ${o}`)}}async convert(e,t){let n=[],o=t?.batchSize??10;for(let r=0;r<e.length;r+=o){let a=e.slice(r,r+o).map(p=>this._convert(p,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var fs=new $,yo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Io=class{ai;db;debug;constructor(e){this.db=new ie,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let o=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:o.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),r=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;r=r.filter(l=>l.score<=a)}this.debug&&console.log(`${fs.whiteBright(`query: ${e}`)}
228
- ${fs.greenBright(JSON.stringify(r.map(a=>`${a.id}, ${a.score}`)))}`);let s=r.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var As=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 xs(i,e){return i.filter(t=>!e.has(t))}function ys(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function ue(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 ta(i,e){return ue(i)===ue(e)?1:0}function na(i,e){let t=ue(i).split(" "),n=ue(e).split(" "),o=ys(t),r=ys(n),s=0;for(let p in o){let u=o[p]??0,c=r[p]??0;s+=Math.min(u,c)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function oa(i,e,t,n=!1){let o=ue(i).split(" "),r=ue(e).split(" "),s=ue(t).split(" "),a=new Set([...As,...o]);r=xs(r,a),s=xs(s,a);let l=0,p=l/r.length,u=l/s.length,c=2*p*u/(p+u);return n?u:c}var ra={emScore:ta,f1Score:na,novelF1ScoreOptimized:oa};var bo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,o=0;for(let 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}),p=await e({prediction:l,example:a});o+=p}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let r=n>0?o/n:0;console.log(`
225
+ `),$i=i=>i.map(t=>{let n=t.title,o=t.type?.name?gs(t.type):"string",r=t.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:qt(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${r})${s}`.trim()}).join(`
226
+ `),Ui=(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?Zr(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)},gs=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)";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function ms(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 Bi=(i,e,t)=>{if(typeof e=="boolean")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 qt(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function qi(i,e){let t=i.history(0,e),n=t.some(r=>r.role==="function");return t.some(r=>r.role==="assistant"&&"functionCalls"in r&&Array.isArray(r.functionCalls)&&r.functionCalls.length>0)&&n}function zi(i,e){let t=i.history(0,e),n=[],o=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),r=t.filter(s=>s.role==="function");for(let s of o)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=r.find(p=>"functionId"in p&&p.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function zt(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let o=e.resultPicker;if((t?qi(t,n):!1)&&t){let l=zi(t,n),p=await o({type:"function",results:l});if(p<0||p>=l.length)throw new Error(`Result picker returned invalid index: ${p}. Must be between 0 and ${l.length-1}`);return p}let s=i.map((l,p)=>({index:p,sample:l.delta})),a=await o({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 hs(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let o=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await zt(o,t,i,e)}import{trace as ji}from"@opentelemetry/api";var ot=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}async route(e,t){let n={},o={},r=[];for(let[a,l]of Object.entries(e)){let p=this.tools.get(this.normalizeToolName(a));if(p&&l!==void 0&&l!==null)try{let u=await this.executeTool(p,l,t);n[a]=u,r.push(p.name)}catch{o[a]=l}else o[a]=l}let s={...o,...n};return{toolResults:n,remainingFields:s}}async executeTool(e,t,n){if(!e.func)throw new Error(`Tool ${e.name} has no handler function`);let o=typeof t=="object"&&t!==null?t:{},r=M.tracer??ji.getTracer("ax");if(!r){let s=e.func;return await s(o,{sessionId:n?.sessionId,traceId:n?.traceId})}return await r.startActiveSpan(`Tool: ${e.name}`,async s=>{try{s.setAttributes?.({"tool.name":e.name,"tool.mode":"prompt"});let a=e.func,l=await a(o,{sessionId:n?.sessionId,traceId:s.spanContext().traceId});return s.addEvent("gen_ai.tool.message",{name:e.name,args:JSON.stringify(o),result:typeof l=="string"?l:JSON.stringify(l??"")}),l}catch(a){throw s.recordException(a),s.addEvent("function.error",{name:e.name,message:a.toString()}),a}finally{s.end()}})}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}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(/^_/,""))}};var jt=class{functionCallMode;tools;router;usePromptMode=!1;constructor(e){this.functionCallMode=e.functionCallMode??"auto",this.tools=e.functions??[],this.functionCallMode==="prompt"&&this.tools.length>0&&(this.usePromptMode=!0,this.router=new ot(this.tools))}setUsePromptMode(e){this.usePromptMode=e,e&&this.tools.length>0&&!this.router&&(this.router=new ot(this.tools))}getMode(){return this.functionCallMode}processSignature(e){return this.usePromptMode&&this.tools.length>0?e.injectToolFields(this.tools):e}async processResults(e,t){return this.usePromptMode&&this.router?(await this.router.route(e,t)).remainingFields:e}isPromptModeEnabled(){return this.usePromptMode}isNativeModeEnabled(){return!this.usePromptMode&&this.tools.length>0}getRouter(){return this.router}};var H=class extends pe{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??fe)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.usage=[],t?.functions&&(this.functions=no(t.functions),t?.functionCallMode&&(this.signatureToolCallingManager=new jt({functionCallMode:t.functionCallMode,functions:this.functions})))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Zn()}updateMeter(e){Zn(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let o=this.signature.getOutputFields().find(r=>r.name===e);if(!o)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let r=o.type?.name;if(!(!r||r==="string"||r==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:o,process:t})}else this.fieldProcessors.push({field:o,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:r,functionCall:s,stepIndex:a}){let{sessionId:l,model:p,rateLimiter:u,stream:d,thinkingTokenBudget:c,showThoughts:m}=n??{},g=await hs(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let x={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),A=a===0,I=this.getLogger(e,n);return await e.chat({chatPrompt:h,functions:r,functionCall:s,modelConfig:x,model:p},{sessionId:l,rateLimiter:u,stream:d,debug:f,debugHideSystemPrompt:!A,thinkingTokenBudget:c,showThoughts:m,traceContext:o,abortSignal:n?.abortSignal,stepIndex:a,logger:I})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:o,span:r,traceContext:s,states:a}){let{sessionId:l,functions:p}=n??{},u=n?.functionCall??this.options?.functionCall,d=n?.strictMode??!1,c=n.model,m=this.usage,g=o===0,h=this.isDebug(e,n),x=this.getLogger(e,n),{functions:f,functionCall:A}=Qr(p,u,g,n),I=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:f,functionCall:A,stepIndex:o});I instanceof ReadableStream?yield*is({ai:e,model:c,res:I,mem:t,sessionId:l,traceId:r?r.spanContext?.().traceId:void 0,functions:f,strictMode:d,span:r,states:a,usage:m,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:x,debug:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter}):yield*as({ai:e,model:c,res:I,mem:t,sessionId:l,traceId:r?r.spanContext?.().traceId:void 0,functions:f,span:r,strictMode:d,states:a,usage:m,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:x,debug:h,functionResultFormatter:n?.functionResultFormatter??this.options?.functionResultFormatter})}async*_forward2(e,t,n,o,r,s){let a=(o?.stopFunction??this.options?.stopFunction)?.toLowerCase(),l=o.maxRetries??this.options?.maxRetries??10,p=o.maxSteps??this.options?.maxSteps??10,u=o.mem??this.options?.mem??new Qe;if(this.signatureToolCallingManager?.getMode()==="auto"&&this.functions&&this.functions.length>0){let I=e.getFeatures(o.model).functions;this.signatureToolCallingManager.setUsePromptMode(!I)}let d;{let A=this.options?.promptTemplate??fe,I=this.signature;this.signatureToolCallingManager?.isPromptModeEnabled()&&(I=this.signatureToolCallingManager.processSignature(this.signature));let b={functions:o?.functions??this.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new A(I,b)}let c,m=performance.now();Array.isArray(t)?(xr(t),c=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):c=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let g=performance.now()-m,h=this.getMetricsInstruments();h&&Lt(h,"prompt_render",g,this.getSignatureName());let x=performance.now();u.addRequest(c,o.sessionId);let f=performance.now()-x;h&&Lt(h,"memory_update",f,this.getSignatureName());e:for(let A=0;A<p;A++){for(let b=0;b<l;b++)try{let y=this.forwardCore({options:o,ai:e,mem:u,stepIndex:A,span:r,traceContext:s,states:n});for await(let w of y)w!==void 0&&(yield{version:b,index:w.index,delta:w.delta});if(ls(u,a,n,o?.sessionId)){let w=this.getMetricsInstruments();w&&Dt(w,A+1,p,this.getSignatureName());continue e}let T=this.getMetricsInstruments();if(T){Dt(T,A+1,p,this.getSignatureName());let w=new Set;n.forEach(P=>{P.functionsExecuted.forEach(k=>w.add(k))}),w.size>0&&Br(T,!0,w.size,!0,!1,this.getSignatureName()),qr(T,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(y){let R,T=this.isDebug(e,o),w=this.getLogger(e,o),P=this.getMetricsInstruments(),k=this.getSignatureName(),F={error:y,errCount:b,logger:w,metricsInstruments:P,signatureName:k,span:r,debug:T};if(r?.recordException(y),y instanceof G)R=Kr(F),d=y;else if(y instanceof ae)R=Wr(F),d=y;else if(y instanceof E)Vr(F);else if(!(y instanceof Z))throw ho(y,e,this.signature);R&&(u.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(R)}],o.sessionId),u.addTag("error",o.sessionId))}let I=this.getMetricsInstruments();throw I&&to(I,l,!1,l,this.getSignatureName()),ho(new Error(`Unable to fix validation error: ${d?.toString()}`),e,this.signature)}throw h&&Dt(h,p,p,this.getSignatureName()),ho(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let o=performance.now(),r=this.createStates(n.sampleCount??1),s=performance.now()-o,a=this.getMetricsInstruments();a&&Lt(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,p=this.functions;if(n?.functions&&(p=no(n.functions,this.functions)),!l){yield*this._forward2(e,t,r,{...n,functions:p});return}let u=p?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},c=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=c?`AxGen > ${c}`:"AxGen",g=l.startSpan(m,{kind:Ki.SERVER,attributes:d}),h=Hi.active(),x=Wi.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,r,{...n,functions:p},g,x),!this.excludeContentFromTrace){let f=r.map(I=>I.values),A=f.length===1?f[0]:f;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let o=performance.now(),r=this.getSignatureName(),s=n?.stream??!1,a=!1,l=0,p=!1;try{let u=this.getMetricsInstruments();u&&Hr(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,r);let d=this._forward1(e,t,n??{}),c=[],m=0,g=0;for await(let y of d)y.version!==m&&(c=[]),m=y.version,c=io(c,y),g++;l=m;let h=performance.now();p=!!n?.resultPicker;let x=await zt(c,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),f=performance.now()-h,I=c[x]?.delta??{};this.signatureToolCallingManager?.isPromptModeEnabled()&&(I=await this.signatureToolCallingManager.processResults(I,{sessionId:n?.sessionId}));let b=Array.isArray(t)?{}:t??{};if(this.trace={...b,...I},p&&this.isDebug(e,n)){let y=this.getLogger(e,n);Xo(c.length,x,f,y)}return a=!0,u&&(jr(u,c.length,p,p?f:void 0,r),zr(u,s,g,void 0,r)),I}catch(u){throw a=!1,u}finally{let u=performance.now()-o,d=this.getMetricsInstruments();d&&($r(d,u,a,r,e.getName(),n?.model?String(n.model):void 0),l>0&&to(d,l,a,n?.maxRetries??10,r))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),r=[],s=0;for await(let p of o)p.version!==s&&(r=[]),s=p.version,r=io(r,p);let a=await zt(r,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=r[a];l&&(yield{version:s,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??M.logger??e.getLogger()}},Ht=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function ho(i,e,t){let n=i instanceof Error?i:new Error(String(i)),o=e.getLastUsedChatModel(),r=e.getLastUsedModelConfig(),s={model:o,maxTokens:r?.maxTokens,streaming:r?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Ht("Generate failed",s,{cause:n})}var Vi=i=>i.replace(/^\W+|\W+$/g,""),Ji=(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 o=i.substring(0,t),r=i.substring(t+n[0].length);return[o,r]},Qi=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Yi=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}},Xi=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Zi=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},fo={trimNonAlphaNum:Vi,splitIntoTwo:Ji,dedup:Qi,extractIdAndText:Yi,extractIndexPrefixedText:Xi,batchArray:Zi};var Ao=class extends H{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."
227
+ query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:o}=await super.forward(e,t,n),r=o.map(a=>{let{id:l}=fo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let p=r[l];return p!==void 0?t.items[p]:void 0}).filter(a=>a!==void 0)}}};var xo=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 o={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(o.duplex="half");let r=await(this.fetch??fetch)(this.tikaUrl,o);if(!r.ok)throw new Error(`Failed to upload file: ${r.statusText}`);return await r.text()}catch(o){throw new Error(`Error converting file: ${o}`)}}async convert(e,t){let n=[],o=t?.batchSize??10;for(let r=0;r<e.length;r+=o){let a=e.slice(r,r+o).map(p=>this._convert(p,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var $d=new $,yo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Io=class{ai;db;debug;constructor(e){this.db=new ie,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let o=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:o.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),r=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;r=r.filter(l=>l.score<=a)}let s=r.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var fs=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 As(i,e){return i.filter(t=>!e.has(t))}function xs(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function ue(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 ea(i,e){return ue(i)===ue(e)?1:0}function ta(i,e){let t=ue(i).split(" "),n=ue(e).split(" "),o=xs(t),r=xs(n),s=0;for(let p in o){let u=o[p]??0,d=r[p]??0;s+=Math.min(u,d)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function na(i,e,t,n=!1){let o=ue(i).split(" "),r=ue(e).split(" "),s=ue(t).split(" "),a=new Set([...fs,...o]);r=As(r,a),s=As(s,a);let l=0,p=l/r.length,u=l/s.length,d=2*p*u/(p+u);return n?u:d}var oa={emScore:ea,f1Score:ta,novelF1ScoreOptimized:na};var bo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,o=0;for(let 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}),p=await e({prediction:l,example:a});o+=p}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let r=n>0?o/n:0;this.ai.getOptions().debug&&console.log(`
229
228
  Performance: `,o,"/",n,"Average Score: ",r,`
230
- `)}};var To=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:o}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=o}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),o=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return console.log("Downloading data from API."),this.rows=await this.fetchDataFromAPI(o),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(r=>{let s={};return t.forEach(a=>{let l=a.split("."),p=r.row;for(let c of l)Object.hasOwn(p,c)&&(p=p[c]);if(!p)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);s[u]=p}),s}).filter(r=>Object.keys(r).length!==0)}};var Is=i=>{console.log(i)},bs=(i=Is)=>{let e=new $,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return o=>{let r="";switch(o.name){case"OptimizationStart":r=`
229
+ `)}};var To=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:o}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=o}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),o=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(o),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(r=>{let s={};return t.forEach(a=>{let l=a.split("."),p=r.row;for(let d of l)Object.hasOwn(p,d)&&(p=p[d]);if(!p)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);s[u]=p}),s}).filter(r=>Object.keys(r).length!==0)}};var ys=i=>{console.log(i)},Is=(i=ys)=>{let e=new $,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return o=>{let r="";switch(o.name){case"OptimizationStart":r=`
231
230
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
232
231
  ${t}
233
232
  ${e.white("Optimizer:")} ${e.cyan(o.value.optimizerType)}
234
233
  ${e.white("Examples:")} ${e.green(o.value.exampleCount.toString())} training, ${e.green(o.value.validationCount.toString())} validation
235
234
  ${e.white("Config:")} ${e.white(JSON.stringify(o.value.config).slice(0,80))}${JSON.stringify(o.value.config).length>80?"...":""}
236
235
  ${n}
237
- `;break;case"RoundProgress":{let s=o.value.configuration||{},a=[];s.temperature!==void 0&&typeof s.temperature=="number"&&a.push(`T=${s.temperature.toFixed(2)}`),s.bootstrappedDemos!==void 0&&a.push(`demos=${s.bootstrappedDemos}`),Object.entries(s).forEach(([u,c])=>{u!=="temperature"&&u!=="bootstrappedDemos"&&u!=="trialNumber"&&typeof c=="number"&&a.push(`${u}=${c.toFixed(2)}`)});let l=o.value.currentScore-o.value.bestScore,p=l>0?e.greenBright(` \u2191${l.toFixed(3)}`):l<0?e.red(` \u2193${Math.abs(l).toFixed(3)}`):"";r=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${o.value.round}/${o.value.totalRounds}`)}`+(s.trialNumber!==void 0?e.gray(` [Trial #${s.trialNumber}]`):"")+`
236
+ `;break;case"RoundProgress":{let s=o.value.configuration||{},a=[];s.temperature!==void 0&&typeof s.temperature=="number"&&a.push(`T=${s.temperature.toFixed(2)}`),s.bootstrappedDemos!==void 0&&a.push(`demos=${s.bootstrappedDemos}`),Object.entries(s).forEach(([u,d])=>{u!=="temperature"&&u!=="bootstrappedDemos"&&u!=="trialNumber"&&typeof d=="number"&&a.push(`${u}=${d.toFixed(2)}`)});let l=o.value.currentScore-o.value.bestScore,p=l>0?e.greenBright(` \u2191${l.toFixed(3)}`):l<0?e.red(` \u2193${Math.abs(l).toFixed(3)}`):"";r=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${o.value.round}/${o.value.totalRounds}`)}`+(s.trialNumber!==void 0?e.gray(` [Trial #${s.trialNumber}]`):"")+`
238
237
  ${e.white("Score:")} ${e.green(o.value.currentScore.toFixed(3))} ${e.white("(best:")} ${e.greenBright(o.value.bestScore.toFixed(3))}${e.white(")")}${p}
239
238
  `+(a.length>0?` ${e.white("Config:")} ${e.cyan(a.join(", "))}
240
239
  `:"")}break;case"EarlyStopping":r=`
@@ -270,7 +269,7 @@ ${t}
270
269
  ${e.white("Config:")} ${e.cyan(JSON.stringify(o.value.config).slice(0,80))}${JSON.stringify(o.value.config).length>80?"...":""}
271
270
  `;break;default:r=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
272
271
  ${e.white(JSON.stringify(o).slice(0,100))}${JSON.stringify(o).length>100?"...":""}
273
- `}i(r)}},sa=(i=Is)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
272
+ `}i(r)}},ra=(i=ys)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
274
273
  ${e}
275
274
  Config: ${JSON.stringify(t.value.config,null,2)}
276
275
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -296,7 +295,7 @@ Score: ${t.value.score.toFixed(3)}
296
295
  Config: ${JSON.stringify(t.value.config)}
297
296
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
298
297
  ${JSON.stringify(t)}
299
- ${e}`}i(n)}},Kt=bs();var Ts={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Wt,ia=i=>{if(Wt)return Wt;if(i)return Wt=pa(i),Wt};var Vt=Ts,aa=i=>{Vt={...Vt,...i}},la=()=>({...Vt}),pa=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"})}),X=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n),r=Vt.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},ua=(i,e,t,n,o)=>{try{let r=X({success:t.toString(),optimizer_type:n,...o?{program_signature:o}:{}});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,r),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,r),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record optimization metric:",r)}},ca=(i,e,t,n,o,r)=>{try{let s=X({optimizer_type:r});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,s),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,s),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,s),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(o,s)}catch(s){console.warn("Failed to record convergence metric:",s)}},da=(i,e,t)=>{try{let n=X({reason:e,optimizer_type:t});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},ma=(i,e,t,n,o)=>{try{let r=X({optimizer_type:n});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,r),i.costUsageCounter&&i.costUsageCounter.add(t,r),o!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(o,r)}catch(r){console.warn("Failed to record resource usage metric:",r)}},ga=(i,e,t)=>{try{let n=X({optimizer_type:t});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},ha=(i,e,t,n)=>{try{let o=X({optimizer_type:n});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)}},fa=(i,e,t,n,o)=>{try{let r=X({operation:e,success:n.toString(),optimizer_type:o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,r),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,r)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,r),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,r))}catch(r){console.warn("Failed to record checkpoint metric:",r)}},Aa=(i,e,t,n,o)=>{try{let r=X({optimizer_type:n});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,r),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,r),o!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(o,r),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,r)}catch(r){console.warn("Failed to record Pareto metric:",r)}},xa=(i,e,t,n,o,r)=>{try{let s=X({optimizer_type:r});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,s),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,s),i.examplesCountGauge&&i.examplesCountGauge.record(n,s),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(o,s)}catch(s){console.warn("Failed to record program complexity metric:",s)}},ya=(i,e,t,n)=>{try{let o=X({metric_type:e,optimizer_type:n});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)}},Ia=(i,e,t,n)=>{try{let o=X({optimizer_type:e});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)}},rt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},Jt=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let o=this.costPerModel[t]||.001;e+=n/1e3*o}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},ce=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 Jt({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=ia(M.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?Kt:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let o=this.getAIService(t,n);return await e(o)}async*compileStream(e,t,n,o){let r=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a);let l,p=(g,h,f,I,A,b,R,y={},x)=>{this.getOptimizerLogger(x)?.({name:"RoundProgress",value:{round:g,totalRounds:x?.maxIterations??0,currentScore:h,bestScore:b,configuration:f}}),this.updateOptimizationProgress(g,h,f,I,A,b,R,y,x)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},c=g=>{this.onProgress?.(g),p(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,o)},d=await this.compile(e,t,n,{...o,overrideOnProgress:c,overrideOnEarlyStop:u}),m=Date.now()-r;return this.recordOptimizationComplete(m,!0,s,a),l&&this.getLogger(o)?.({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,o){let r=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,o),l=await this.generateConstraintSolutions(e,t,n,o),p=[...a,...l],u=this.findParetoFrontier(p),c=this.calculateHypervolume(u);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,p.length,"base_optimizer",c);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:c,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:c,strategy:"weighted_combinations_and_constraints",numSolutions:p.length}}}async generateWeightedSolutions(e,t,n,o){let r=[];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,o),s),l=await n({prediction:a,example:s}),p=Object.keys(l),u=this.generateWeightCombinations(p);for(let c=0;c<u.length;c++){let d=u[c],m=async({prediction:g,example:h})=>{let f=await n({prediction:g,example:h}),I=0;for(let[A,b]of Object.entries(f))I+=b*(d[A]||0);return I};try{let g=await this.compile(e,t,m,{...o,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);r.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return r}async generateConstraintSolutions(e,t,n,o){let r=[];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,o),s),l=await n({prediction:a,example:s}),p=Object.keys(l);for(let u of p){let c=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[u]||0,f=0;for(let[I,A]of Object.entries(g))I!==u&&A<.3&&(f+=(.3-A)*2);return h-f};try{let d=await this.compile(e,t,c,{...o,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);r.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return r}generateWeightCombinations(e){let t=[];for(let o of e){let r={};for(let s of e)r[s]=s===o?1:0;t.push(r)}let n={};for(let o of e)n[o]=1/e.length;if(t.push(n),e.length===2){let[o,r]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[o]:s,[r]:a})}}if(e.length===3){let[o,r,s]=e;t.push({[o]:.5,[r]:.3,[s]:.2},{[o]:.3,[r]:.5,[s]:.2},{[o]:.2,[r]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,o){let r=new H(e.getSignature());t.demos&&r.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(o.length*.2))),l=o.slice(-a),p={},u=l;for(let d of u)try{let m=await r.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[h,f]of Object.entries(g))p[h]||(p[h]=[]),p[h].push(f)}catch{}let c={};for(let[d,m]of Object.entries(p))c[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return c}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n],r=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,o.scores)){r=!0;break}this.dominates(o.scores,l.scores)&&s++}r||t.push({demos:o.demos||[],scores:o.scores,configuration:o.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),o=!0,r=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){o=!1;break}a>l&&(r=!0)}return o&&r}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[o,r]=n,s=0,a=[...e].sort((p,u)=>(u.scores[o]||0)-(p.scores[o]||0)),l=0;for(let p of a){let u=p.scores[o]||0,c=p.scores[r]||0;s+=u*(c-l),l=Math.max(l,c)}return s}}async saveCheckpoint(e,t,n,o,r={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),p=!1,u;try{let c={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:o,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:r,examples:[]};u=await a(c),p=!0}catch(c){throw p=!1,c}finally{let c=Date.now()-l;this.recordCheckpointMetrics("save",c,p,e)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let o=Date.now(),r=!1,s=null;try{s=await n(e),r=s!==null}catch(a){throw r=!1,a}finally{let a=Date.now()-o;this.recordCheckpointMetrics("load",a,r,"unknown")}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,o,r,s,a,l={},p){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,p)&&await this.saveCheckpoint(o,r,s,a,l,p),this.getOptimizerLogger(p)?.({name:"RoundProgress",value:{round:e,totalRounds:p?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,o,r={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,o,{...r,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){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;xa(this.metricsInstruments,n,o,0,0,e)}Ia(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,o){if(!this.metricsInstruments)return;ua(this.metricsInstruments,e,t,n,o),ga(this.metricsInstruments,e,n);let r=this.costTracker?.getCurrentCost()??0,s=this.costTracker?.getTotalTokens()??0;ma(this.metricsInstruments,s,r,n)}recordConvergenceMetrics(e,t,n,o,r){this.metricsInstruments&&ca(this.metricsInstruments,e,t,n,o,r)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&da(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&ha(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,o){this.metricsInstruments&&fa(this.metricsInstruments,e,t,n,o)}recordParetoMetrics(e,t,n,o){this.metricsInstruments&&Aa(this.metricsInstruments,e,t,n,o)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&ya(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??M.optimizerLogger??Kt}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let o=this.stats.convergenceInfo.converged,r=this.stats.totalCalls,s=r>0?this.stats.successfulDemos/r*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${o?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(o||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 p=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:p}}async logOptimizationComplete(e,t,n,o,r){let s=this.getOptimizerLogger(o);s&&s(r?{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:r.humanExplanation,recommendations:r.recommendations,performanceAssessment:r.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=[]}};var st=class extends ce{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,o,r){let s=Date.now(),a=r?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let p=Ta([...t],this.maxExamples),u=this.traces.length;for(let c=0;c<p.length;c+=this.batchSize){c>0&&(l.modelConfig.temperature=.7+.001*c);let d=p.slice(c,c+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(I=>I!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let I={...l,maxRetries:1};f=await e.forward(h,m,I),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await o({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(I){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${I instanceof Error?I.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,o){this.validateExamples(t,!1);let r=o?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<r&&(await this.compileRound(e,t,l,n,o),!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=ba(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},o),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function ba(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let o=e.get(n.programId);o&&o.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,o)=>{t.push({traces:n,programId:o})}),t}var Ta=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1)),r=t[n],s=t[o];if(!r||!s)throw new Error("Invalid array elements");[t[n],t[o]]=[s,r]}return t.slice(0,e)};function Ra(i){return D.create(i)}function Ae(i,e){let t=typeof i=="string"?D.create(i):i;return new H(t,e)}var Qt=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 o=Date.now();for(;Date.now()-o<n;){let r=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(r.status))return r;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${r.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}`,o=null;for(let r=0;r<this.retryAttempts;r++)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){o=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${r+1} failed: ${s}`}),r<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,r))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${o?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Ro=class extends ce{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 Qt(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let r=e.results.findIndex(s=>!s.isError);return r>=0?r:0}let t=new Map;for(let r of e.results){let s=JSON.stringify(r.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:r.index})}let n="",o={count:-1,firstIndex:0};for(let[r,s]of t.entries())s.count>o.count&&(o=s,n=r);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 o=`
298
+ ${e}`}i(n)}},Kt=Is();var bs={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Wt,sa=i=>{if(Wt)return Wt;if(i)return Wt=la(i),Wt};var Vt=bs,ia=i=>{Vt={...Vt,...i}},aa=()=>({...Vt}),la=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"})}),X=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let o=String(n),r=Vt.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},pa=(i,e,t,n,o)=>{try{let r=X({success:t.toString(),optimizer_type:n,...o?{program_signature:o}:{}});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,r),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,r),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record optimization metric:",r)}},ua=(i,e,t,n,o,r)=>{try{let s=X({optimizer_type:r});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,s),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,s),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,s),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(o,s)}catch(s){console.warn("Failed to record convergence metric:",s)}},ca=(i,e,t)=>{try{let n=X({reason:e,optimizer_type:t});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},da=(i,e,t,n,o)=>{try{let r=X({optimizer_type:n});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,r),i.costUsageCounter&&i.costUsageCounter.add(t,r),o!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(o,r)}catch(r){console.warn("Failed to record resource usage metric:",r)}},ma=(i,e,t)=>{try{let n=X({optimizer_type:t});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},ga=(i,e,t,n)=>{try{let o=X({optimizer_type:n});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)}},ha=(i,e,t,n,o)=>{try{let r=X({operation:e,success:n.toString(),optimizer_type:o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,r),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,r)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,r),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,r))}catch(r){console.warn("Failed to record checkpoint metric:",r)}},fa=(i,e,t,n,o)=>{try{let r=X({optimizer_type:n});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,r),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,r),o!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(o,r),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,r)}catch(r){console.warn("Failed to record Pareto metric:",r)}},Aa=(i,e,t,n,o,r)=>{try{let s=X({optimizer_type:r});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,s),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,s),i.examplesCountGauge&&i.examplesCountGauge.record(n,s),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(o,s)}catch(s){console.warn("Failed to record program complexity metric:",s)}},xa=(i,e,t,n)=>{try{let o=X({metric_type:e,optimizer_type:n});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)}},ya=(i,e,t,n)=>{try{let o=X({optimizer_type:e});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)}},rt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},Jt=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let o=this.costPerModel[t]||.001;e+=n/1e3*o}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},ce=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 Jt({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=sa(M.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?Kt:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let o=this.getAIService(t,n);return await e(o)}async*compileStream(e,t,n,o){let r=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a);let l,p=(g,h,x,f,A,I,b,y={},R)=>{this.getOptimizerLogger(R)?.({name:"RoundProgress",value:{round:g,totalRounds:R?.maxIterations??0,currentScore:h,bestScore:I,configuration:x}}),this.updateOptimizationProgress(g,h,x,f,A,I,b,y,R)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},d=g=>{this.onProgress?.(g),p(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,o)},c=await this.compile(e,t,n,{...o,overrideOnProgress:d,overrideOnEarlyStop:u}),m=Date.now()-r;return this.recordOptimizationComplete(m,!0,s,a),l&&this.getLogger(o)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:c.demos,stats:c.stats,bestScore:c.bestScore,finalConfiguration:c.finalConfiguration,scoreHistory:c.scoreHistory,configurationHistory:c.configurationHistory}}async compilePareto(e,t,n,o){let r=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,o),l=await this.generateConstraintSolutions(e,t,n,o),p=[...a,...l],u=this.findParetoFrontier(p),d=this.calculateHypervolume(u);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,p.length,"base_optimizer",d);let c=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:c,paretoFront:u,hypervolume:d,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:d,strategy:"weighted_combinations_and_constraints",numSolutions:p.length}}}async generateWeightedSolutions(e,t,n,o){let r=[];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,o),s),l=await n({prediction:a,example:s}),p=Object.keys(l),u=this.generateWeightCombinations(p);for(let d=0;d<u.length;d++){let c=u[d],m=async({prediction:g,example:h})=>{let x=await n({prediction:g,example:h}),f=0;for(let[A,I]of Object.entries(x))f+=I*(c[A]||0);return f};try{let g=await this.compile(e,t,m,{...o,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);r.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:c,strategy:"weighted_combination"}})}catch{}}return r}async generateConstraintSolutions(e,t,n,o){let r=[];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,o),s),l=await n({prediction:a,example:s}),p=Object.keys(l);for(let u of p){let d=async({prediction:c,example:m})=>{let g=await n({prediction:c,example:m}),h=g[u]||0,x=0;for(let[f,A]of Object.entries(g))f!==u&&A<.3&&(x+=(.3-A)*2);return h-x};try{let c=await this.compile(e,t,d,{...o,verbose:!1}),m=await this.evaluateWithMultiObjective(e,c,n,t);r.push({scores:m,demos:c.demos,configuration:{...c.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return r}generateWeightCombinations(e){let t=[];for(let o of e){let r={};for(let s of e)r[s]=s===o?1:0;t.push(r)}let n={};for(let o of e)n[o]=1/e.length;if(t.push(n),e.length===2){let[o,r]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[o]:s,[r]:a})}}if(e.length===3){let[o,r,s]=e;t.push({[o]:.5,[r]:.3,[s]:.2},{[o]:.3,[r]:.5,[s]:.2},{[o]:.2,[r]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,o){let r=new H(e.getSignature());t.demos&&r.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(o.length*.2))),l=o.slice(-a),p={},u=l;for(let c of u)try{let m=await r.forward(this.studentAI,c),g=await n({prediction:m,example:c});for(let[h,x]of Object.entries(g))p[h]||(p[h]=[]),p[h].push(x)}catch{}let d={};for(let[c,m]of Object.entries(p))d[c]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return d}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n],r=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,o.scores)){r=!0;break}this.dominates(o.scores,l.scores)&&s++}r||t.push({demos:o.demos||[],scores:o.scores,configuration:o.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),o=!0,r=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){o=!1;break}a>l&&(r=!0)}return o&&r}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[o,r]=n,s=0,a=[...e].sort((p,u)=>(u.scores[o]||0)-(p.scores[o]||0)),l=0;for(let p of a){let u=p.scores[o]||0,d=p.scores[r]||0;s+=u*(d-l),l=Math.max(l,d)}return s}}async saveCheckpoint(e,t,n,o,r={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),p=!1,u;try{let d={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:o,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:r,examples:[]};u=await a(d),p=!0}catch(d){throw p=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,p,e)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let o=Date.now(),r=!1,s=null;try{s=await n(e),r=s!==null}catch(a){throw r=!1,a}finally{let a=Date.now()-o;this.recordCheckpointMetrics("load",a,r,"unknown")}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,o,r,s,a,l={},p){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,p)&&await this.saveCheckpoint(o,r,s,a,l,p),this.getOptimizerLogger(p)?.({name:"RoundProgress",value:{round:e,totalRounds:p?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,o,r={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,o,{...r,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){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;Aa(this.metricsInstruments,n,o,0,0,e)}ya(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,o){if(!this.metricsInstruments)return;pa(this.metricsInstruments,e,t,n,o),ma(this.metricsInstruments,e,n);let r=this.costTracker?.getCurrentCost()??0,s=this.costTracker?.getTotalTokens()??0;da(this.metricsInstruments,s,r,n)}recordConvergenceMetrics(e,t,n,o,r){this.metricsInstruments&&ua(this.metricsInstruments,e,t,n,o,r)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&ca(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&ga(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,o){this.metricsInstruments&&ha(this.metricsInstruments,e,t,n,o)}recordParetoMetrics(e,t,n,o){this.metricsInstruments&&fa(this.metricsInstruments,e,t,n,o)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&xa(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??M.optimizerLogger??Kt}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let o=this.stats.convergenceInfo.converged,r=this.stats.totalCalls,s=r>0?this.stats.successfulDemos/r*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${o?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(o||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 p=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:p}}async logOptimizationComplete(e,t,n,o,r){let s=this.getOptimizerLogger(o);s&&s(r?{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:r.humanExplanation,recommendations:r.recommendations,performanceAssessment:r.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=[]}};var st=class extends ce{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,o,r){let s=Date.now(),a=r?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let p=ba([...t],this.maxExamples),u=this.traces.length;for(let d=0;d<p.length;d+=this.batchSize){d>0&&(l.modelConfig.temperature=.7+.001*d);let c=p.slice(d,d+this.batchSize);for(let m of c){if(!m||typeof m!="object")continue;let g=t.filter(f=>f!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let x;try{let f={...l,maxRetries:1};x=await e.forward(h,m,f),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(x).length/4),await o({prediction:x,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(f){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${f instanceof Error?f.message:"Unknown error"}`),x={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let c=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:c>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(c>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,o){this.validateExamples(t,!1);let r=o?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<r&&(await this.compileRound(e,t,l,n,o),!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=Ia(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},o),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Ia(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let o=e.get(n.programId);o&&o.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,o)=>{t.push({traces:n,programId:o})}),t}var ba=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1)),r=t[n],s=t[o];if(!r||!s)throw new Error("Invalid array elements");[t[n],t[o]]=[s,r]}return t.slice(0,e)};function Ta(i){return L.create(i)}function Ae(i,e){let t=typeof i=="string"?L.create(i):i;return new H(t,e)}var Qt=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 o=Date.now();for(;Date.now()-o<n;){let r=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(r.status))return r;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${r.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}`,o=null;for(let r=0;r<this.retryAttempts;r++)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){o=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${r+1} failed: ${s}`}),r<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,r))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${o?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Ro=class extends ce{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 Qt(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let r=e.results.findIndex(s=>!s.isError);return r>=0?r:0}let t=new Map;for(let r of e.results){let s=JSON.stringify(r.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:r.index})}let n="",o={count:-1,firstIndex:0};for(let[r,s]of t.entries())s.count>o.count&&(o=s,n=r);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 o=`
300
299
  Analyze this language model program and provide a concise summary of its purpose and structure.
301
300
 
302
301
  Program Signature: ${e.getSignature()}
@@ -336,7 +335,7 @@ Requirements:
336
335
  5. Keep it concise but comprehensive
337
336
 
338
337
  Generate a single, well-crafted instruction:
339
- Instruction:`;try{let m=(await Ae('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:o??"",datasetSummary:r??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let p=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],u=p[t%p.length]||p[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let o=[],r=this.getTeacherOrStudentAI(t),s,a;this.programAwareProposer&&(s=await this.generateProgramSummary(e,r)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],r));let l=this.tipAwareProposer?this.generateTips():[];for(let p=0;p<this.numCandidates;p++){let u=l.length>0?p%l.length:-1,c=u>=0?l[u]:void 0,d=await this.generateInstruction({tip:c,candidateIndex:p,ai:r,programSummary:s,datasetSummary:a,previousInstructions:o});o.push(d)}return o}async bootstrapFewShotExamples(e,t,n){return(await new st({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 o=Math.floor(Math.random()*e.length);if(!n.has(o)){n.add(o);let r=e[o];r&&t.push(r)}}return t}applyConfigToProgram(e,t,n,o){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(o.slice(0,t.labeledExamples))}async compile(e,t,n,o){let r=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),o?.auto&&this.configureAuto(o.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,o)}applyConfigToAxGen(e,t,n,o){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(o.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,o){if(!this.pythonClient)throw new Error("Python client not initialized");let r=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let s=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={study_name:s,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},l=await this.pythonClient.createOptimizationJob(a);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:l.job_id,numTrials:this.numTrials}}});let u=Number.NEGATIVE_INFINITY,c,d=0,m=0;for(let R=0;R<this.numTrials;R++)try{let y=await this.pythonClient.suggestParameters(s),x=y.params.temperature,T=y.params.bootstrappedDemos,v=this.optimizeTopP?y.params.topP:void 0;if(x===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(y)}`);if(T===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(y)}`);let P=!this.minibatch||this.minibatchFullEvalSteps>0&&R%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let be=Math.min(this.minibatchSize,t.length),B=new Set;for(;B.size<be;)B.add(Math.floor(Math.random()*t.length));return Array.from(B).map(Ms=>t[Ms])})(),U=await this.evaluateConfiguration(e,n,{temperature:x,bootstrappedDemos:T,topP:v},P);d++,await this.pythonClient.evaluateTrial({study_name:s,trial_number:y.trial_number,value:U}),U>u+this.minImprovementThreshold?(u=U,c={temperature:x,bootstrappedDemos:T,...v!==void 0?{topP:v}:{},trialNumber:y.trial_number},m=0):m+=1,this.currentRound=R+1;let K={temperature:x,bootstrappedDemos:T,...v!==void 0?{topP:v}:{},trialNumber:y.trial_number};if(this.localScoreHistory.push(U),this.localConfigurationHistory.push(K),await this.updateOptimizationProgress(this.currentRound,U,K,"MiPRO (Python)",{sampler:"TPESampler"},u,c),this.onProgress?.({round:R+1,totalRounds:this.numTrials,currentScore:U,bestScore:u,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-r,successfulExamples:d,totalExamples:t.length}),this.earlyStoppingTrials>0&&m>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:u,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let g=u,h={},f=[];try{let R=await this.pythonClient.getStudyResults(s);if(g=R.best_value||u,h=R.best_params||{},h&&Object.keys(h).length>0){let y=h.bootstrappedDemos||0;y>0&&(f=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),f=f.slice(0,y))}}catch{}let I;try{let y=await Ae('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:g,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:h||{}});I={humanExplanation:y.humanExplanation??"",recommendations:y.recommendations??[],performanceAssessment:y.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,h,o,I);try{await this.pythonClient.deleteStudy(s)}catch{}this.stats.bestScore=g;let A=new H(e.getSignature());f.length>0&&A.setDemos(f),h.temperature&&(A._optimizedModelConfig={temperature:h.temperature});let b=new rt({bestScore:g,stats:this.stats,instruction:void 0,demos:f,examples:[],modelConfig:{temperature:h.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-r,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return{bestScore:g,demos:f,stats:this.stats,optimizedGen:A,optimizedProgram:b,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}async evaluateConfiguration(e,t,n,o){let r=0,s=0,a=0,l=o,p=[];if(n.bootstrappedDemos>0)try{p=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{p=[]}for(let u of l)try{p.length>0&&e.setDemos?.(p);let c=await e.forward(this.studentAI,u,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let d=await t({prediction:c,example:u});if(typeof d=="number"&&!Number.isNaN(d)){r+=d,s++;let m=typeof this.targetScore=="number"?this.targetScore:.5;d>=m&&a++}}catch(c){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof c=="string"?c:String(c)})}return this.stats.successfulDemos+=a,s>0?r/s:0}};var it=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let o=e.toString(),r=Array.from(o.matchAll(/state\.(\w+)/g));for(let s of r)s[1]&&!n.includes(s[1])&&n.push(s[1]);if(n.length===0)try{let s=this.createDependencyTracker(n);e(s)}catch{}}catch(o){console.debug("Dependency analysis failed:",o)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(o,r){typeof r=="string"&&!t.includes(r)&&t.push(r);let s=o[r];return s&&typeof s=="object"?n.createTrackingProxy(s,t):s},has(o,r){return typeof r=="string"&&!t.includes(r)&&t.push(r),r in o}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let s of n)s[1]&&!t.includes(s[1])&&t.push(s[1]);let o=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let s of o)s[1]&&!t.includes(s[1])&&t.push(s[1]);let r=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let s of r)for(let a=1;a<s.length;a++)s[a]&&!t.includes(s[a])&&t.push(s[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function xe(i,e,t){if(!t||t<=0||t>=i.length){let o=i.map((r,s)=>e(r,s));return Promise.all(o)}let n=new Array(i.length);for(let o=0;o<i.length;o+=t){let s=i.slice(o,o+t).map((l,p)=>{let u=o+p;return e(l,u).then(c=>({result:c,originalIndex:u}))}),a=await Promise.all(s);for(let{result:l,originalIndex:p}of a)n[p]=l}return n}var at=class{steps=[];parallelGroups=[];analyzer=new it;initialFields=new Set;addExecutionStep(e,t,n,o,r,s,a){let l=[],p=[],u=o||"map";if(t&&n)u="execute",l=this.analyzer.analyzeMappingDependencies(n,t),p=[`${t}Result`];else if(u==="map"&&r)p=this.analyzeMapTransformation(r),l=this.getAllProducedFields();else if(u==="parallel-map"){if(Array.isArray(r)){let d=new Set;for(let m of r)this.analyzeMapTransformation(m).forEach(h=>d.add(h));p=Array.from(d)}else r?p=this.analyzeMapTransformation(r):p=["_parallelMapResult"];l=this.getAllProducedFields()}else if(u==="merge"){if(s?.resultKey)p=[s.resultKey];else{let m=this.analyzeBranchMergeFields();p=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(u==="parallel")p=["_parallelResults"],l=this.getAllProducedFields();else if(u==="derive")if(a?.outputFieldName&&a?.inputFieldName){p=[a.outputFieldName];let d=r?this.analyzer.analyzeMappingDependencies(r,"derive"):[];l=[a.inputFieldName,...d].filter((m,g,h)=>h.indexOf(m)===g)}else p=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(u="map",l=this.getAllProducedFields(),p=["_mapResult"]):e.toString().includes("_parallelResults")&&(p=["_parallelResults"],l=this.getAllProducedFields());for(let d of l)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let c={type:u,nodeName:t,dependencies:l,produces:p,stepFunction:e,stepIndex:this.steps.length};this.steps.push(c)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),r=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(r&&typeof r=="object"&&"then"in r)return this.analyzeStepFunctionSource(e);if(r&&typeof r=="object"&&!Array.isArray(r)){let a=Object.keys(r).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let r=n.map(s=>{let a=s.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}let o=t.match(/state\.(\w+)\s*=/g);if(o){let r=o.map(s=>{let a=s.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let o=[];for(let r of this.steps){if(e.has(r.stepIndex))continue;if(r.dependencies.length===0||r.dependencies.every(a=>t.has(a))){if(r.type==="merge"&&o.length>0)continue;if(o.push(r),e.add(r.stepIndex),r.type==="merge")break}}if(o.length>0){for(let r of o)r.produces.forEach(s=>t.add(s));this.parallelGroups.push({level:n,steps:o}),n++}else{let r=this.steps.filter(s=>!e.has(s.stepIndex));if(r.length>0){let s=r[0];e.add(s.stepIndex),s.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[s]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let o=n.steps[0];o&&t.push(o.stepFunction)}else if(n.steps.length>1){let o=async(r,s)=>{let a=await xe(n.steps,async u=>await u.stepFunction(r,s),e);if(a.some(u=>u&&typeof u=="object"&&"_parallelResults"in u)){let u=a.find(c=>c&&typeof c=="object"&&"_parallelResults"in c);return u||r}let p=r;for(let u of a)p={...p,...u};return p};t.push(o)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};import{context as Sa,SpanKind as va,trace as Oa}from"@opentelemetry/api";var Rs=i=>{console.log(i)},ye=(i,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,o]of Object.entries(i))if(typeof o=="string"&&o.length>100)t[n]=`${o.substring(0,100)}...`;else if(Array.isArray(o)&&o.length>3)t[n]=[...o.slice(0,3),`... (${o.length-3} more)`];else if(typeof o=="object"&&o!==null){let r=JSON.stringify(o);r.length>200?t[n]=`${r.substring(0,200)}...`:t[n]=o}else t[n]=o;return JSON.stringify(t,null,2)},Ie=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,Yt=(i=Rs)=>{let e=new $,t=e.gray(`${"\u2501".repeat(80)}
338
+ Instruction:`;try{let m=(await Ae('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:o??"",datasetSummary:r??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let p=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],u=p[t%p.length]||p[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let o=[],r=this.getTeacherOrStudentAI(t),s,a;this.programAwareProposer&&(s=await this.generateProgramSummary(e,r)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],r));let l=this.tipAwareProposer?this.generateTips():[];for(let p=0;p<this.numCandidates;p++){let u=l.length>0?p%l.length:-1,d=u>=0?l[u]:void 0,c=await this.generateInstruction({tip:d,candidateIndex:p,ai:r,programSummary:s,datasetSummary:a,previousInstructions:o});o.push(c)}return o}async bootstrapFewShotExamples(e,t,n){return(await new st({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 o=Math.floor(Math.random()*e.length);if(!n.has(o)){n.add(o);let r=e[o];r&&t.push(r)}}return t}applyConfigToProgram(e,t,n,o){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(o.slice(0,t.labeledExamples))}async compile(e,t,n,o){let r=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),o?.auto&&this.configureAuto(o.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,o)}applyConfigToAxGen(e,t,n,o){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(o.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,o){if(!this.pythonClient)throw new Error("Python client not initialized");let r=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let s=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={study_name:s,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},l=await this.pythonClient.createOptimizationJob(a);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:l.job_id,numTrials:this.numTrials}}});let u=Number.NEGATIVE_INFINITY,d,c=0,m=0;for(let b=0;b<this.numTrials;b++)try{let y=await this.pythonClient.suggestParameters(s),R=y.params.temperature,T=y.params.bootstrappedDemos,w=this.optimizeTopP?y.params.topP:void 0;if(R===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(y)}`);if(T===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(y)}`);let k=!this.minibatch||this.minibatchFullEvalSteps>0&&b%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let be=Math.min(this.minibatchSize,t.length),z=new Set;for(;z.size<be;)z.add(Math.floor(Math.random()*t.length));return Array.from(z).map(Os=>t[Os])})(),F=await this.evaluateConfiguration(e,n,{temperature:R,bootstrappedDemos:T,topP:w},k);c++,await this.pythonClient.evaluateTrial({study_name:s,trial_number:y.trial_number,value:F}),F>u+this.minImprovementThreshold?(u=F,d={temperature:R,bootstrappedDemos:T,...w!==void 0?{topP:w}:{},trialNumber:y.trial_number},m=0):m+=1,this.currentRound=b+1;let K={temperature:R,bootstrappedDemos:T,...w!==void 0?{topP:w}:{},trialNumber:y.trial_number};if(this.localScoreHistory.push(F),this.localConfigurationHistory.push(K),await this.updateOptimizationProgress(this.currentRound,F,K,"MiPRO (Python)",{sampler:"TPESampler"},u,d),this.onProgress?.({round:b+1,totalRounds:this.numTrials,currentScore:F,bestScore:u,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-r,successfulExamples:c,totalExamples:t.length}),this.earlyStoppingTrials>0&&m>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:u,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let g=u,h={},x=[];try{let b=await this.pythonClient.getStudyResults(s);if(g=b.best_value||u,h=b.best_params||{},h&&Object.keys(h).length>0){let y=h.bootstrappedDemos||0;y>0&&(x=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),x=x.slice(0,y))}}catch{}let f;try{let y=await Ae('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:g,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:h||{}});f={humanExplanation:y.humanExplanation??"",recommendations:y.recommendations??[],performanceAssessment:y.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,h,o,f);try{await this.pythonClient.deleteStudy(s)}catch{}this.stats.bestScore=g;let A=new H(e.getSignature());x.length>0&&A.setDemos(x),h.temperature&&(A._optimizedModelConfig={temperature:h.temperature});let I=new rt({bestScore:g,stats:this.stats,instruction:void 0,demos:x,examples:[],modelConfig:{temperature:h.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-r,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return{bestScore:g,demos:x,stats:this.stats,optimizedGen:A,optimizedProgram:I,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}async evaluateConfiguration(e,t,n,o){let r=0,s=0,a=0,l=o,p=[];if(n.bootstrappedDemos>0)try{p=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{p=[]}for(let u of l)try{p.length>0&&e.setDemos?.(p);let d=await e.forward(this.studentAI,u,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let c=await t({prediction:d,example:u});if(typeof c=="number"&&!Number.isNaN(c)){r+=c,s++;let m=typeof this.targetScore=="number"?this.targetScore:.5;c>=m&&a++}}catch(d){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof d=="string"?d:String(d)})}return this.stats.successfulDemos+=a,s>0?r/s:0}};var it=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let o=e.toString(),r=Array.from(o.matchAll(/state\.(\w+)/g));for(let s of r)s[1]&&!n.includes(s[1])&&n.push(s[1]);if(n.length===0)try{let s=this.createDependencyTracker(n);e(s)}catch{}}catch(o){console.debug("Dependency analysis failed:",o)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(o,r){typeof r=="string"&&!t.includes(r)&&t.push(r);let s=o[r];return s&&typeof s=="object"?n.createTrackingProxy(s,t):s},has(o,r){return typeof r=="string"&&!t.includes(r)&&t.push(r),r in o}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let s of n)s[1]&&!t.includes(s[1])&&t.push(s[1]);let o=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let s of o)s[1]&&!t.includes(s[1])&&t.push(s[1]);let r=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let s of r)for(let a=1;a<s.length;a++)s[a]&&!t.includes(s[a])&&t.push(s[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function xe(i,e,t){if(!t||t<=0||t>=i.length){let o=i.map((r,s)=>e(r,s));return Promise.all(o)}let n=new Array(i.length);for(let o=0;o<i.length;o+=t){let s=i.slice(o,o+t).map((l,p)=>{let u=o+p;return e(l,u).then(d=>({result:d,originalIndex:u}))}),a=await Promise.all(s);for(let{result:l,originalIndex:p}of a)n[p]=l}return n}var at=class{steps=[];parallelGroups=[];analyzer=new it;initialFields=new Set;addExecutionStep(e,t,n,o,r,s,a){let l=[],p=[],u=o||"map";if(t&&n)u="execute",l=this.analyzer.analyzeMappingDependencies(n,t),p=[`${t}Result`];else if(u==="map"&&r)p=this.analyzeMapTransformation(r),l=this.getAllProducedFields();else if(u==="parallel-map"){if(Array.isArray(r)){let c=new Set;for(let m of r)this.analyzeMapTransformation(m).forEach(h=>c.add(h));p=Array.from(c)}else r?p=this.analyzeMapTransformation(r):p=["_parallelMapResult"];l=this.getAllProducedFields()}else if(u==="merge"){if(s?.resultKey)p=[s.resultKey];else{let m=this.analyzeBranchMergeFields();p=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(u==="parallel")p=["_parallelResults"],l=this.getAllProducedFields();else if(u==="derive")if(a?.outputFieldName&&a?.inputFieldName){p=[a.outputFieldName];let c=r?this.analyzer.analyzeMappingDependencies(r,"derive"):[];l=[a.inputFieldName,...c].filter((m,g,h)=>h.indexOf(m)===g)}else p=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(u="map",l=this.getAllProducedFields(),p=["_mapResult"]):e.toString().includes("_parallelResults")&&(p=["_parallelResults"],l=this.getAllProducedFields());for(let c of l)this.getAllProducedFields().includes(c)||this.initialFields.add(c);let d={type:u,nodeName:t,dependencies:l,produces:p,stepFunction:e,stepIndex:this.steps.length};this.steps.push(d)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),r=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(r&&typeof r=="object"&&"then"in r)return this.analyzeStepFunctionSource(e);if(r&&typeof r=="object"&&!Array.isArray(r)){let a=Object.keys(r).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let r=n.map(s=>{let a=s.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}let o=t.match(/state\.(\w+)\s*=/g);if(o){let r=o.map(s=>{let a=s.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(r.length>0)return r}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let o=[];for(let r of this.steps){if(e.has(r.stepIndex))continue;if(r.dependencies.length===0||r.dependencies.every(a=>t.has(a))){if(r.type==="merge"&&o.length>0)continue;if(o.push(r),e.add(r.stepIndex),r.type==="merge")break}}if(o.length>0){for(let r of o)r.produces.forEach(s=>t.add(s));this.parallelGroups.push({level:n,steps:o}),n++}else{let r=this.steps.filter(s=>!e.has(s.stepIndex));if(r.length>0){let s=r[0];e.add(s.stepIndex),s.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[s]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let o=n.steps[0];o&&t.push(o.stepFunction)}else if(n.steps.length>1){let o=async(r,s)=>{let a=await xe(n.steps,async u=>await u.stepFunction(r,s),e);if(a.some(u=>u&&typeof u=="object"&&"_parallelResults"in u)){let u=a.find(d=>d&&typeof d=="object"&&"_parallelResults"in d);return u||r}let p=r;for(let u of a)p={...p,...u};return p};t.push(o)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};import{context as wa,SpanKind as Sa,trace as va}from"@opentelemetry/api";var Ts=i=>{console.log(i)},ye=(i,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,o]of Object.entries(i))if(typeof o=="string"&&o.length>100)t[n]=`${o.substring(0,100)}...`;else if(Array.isArray(o)&&o.length>3)t[n]=[...o.slice(0,3),`... (${o.length-3} more)`];else if(typeof o=="object"&&o!==null){let r=JSON.stringify(o);r.length>200?t[n]=`${r.substring(0,200)}...`:t[n]=o}else t[n]=o;return JSON.stringify(t,null,2)},Ie=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,Yt=(i=Ts)=>{let e=new $,t=e.gray(`${"\u2501".repeat(80)}
340
339
  `),n=e.gray(`${"\u2500".repeat(40)}
341
340
  `);return o=>{let r="";switch(o.name){case"FlowStart":r=`
342
341
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -371,7 +370,7 @@ ${e.redBright("\u274C [ AXFLOW ERROR ]")}
371
370
  ${t}`,o.stepIndex!==void 0&&(r+=`${e.white("Step:")} ${e.yellow(o.stepIndex.toString())}`,o.stepType&&(r+=` ${e.gray(`(${o.stepType})`)}`),o.nodeName&&(r+=` ${e.cyan(`Node: ${o.nodeName}`)}`),r+=`
372
371
  `),r+=`${e.white("Error:")} ${e.red(o.error)}
373
372
  `,o.state&&(r+=`${e.white("State:")} ${e.gray(ye(o.state,!0))}
374
- `),r+=t;break;default:r=e.gray(JSON.stringify(o,null,2))}i(r)}},Ca=(i=Rs)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let o="";switch(n.name){case"FlowStart":o=`
373
+ `),r+=t;break;default:r=e.gray(JSON.stringify(o,null,2))}i(r)}},Ra=(i=Ts)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let o="";switch(n.name){case"FlowStart":o=`
375
374
  [ AXFLOW START ]
376
375
  ${e}
377
376
  `,o+=`Input Fields: ${n.inputFields.join(", ")}
@@ -415,9 +414,9 @@ ${e}
415
414
  `),o+=`Error: ${n.error}
416
415
  `,n.state&&(o+=`State: ${ye(n.state,!0)}
417
416
  `),o+=`${e}
418
- `;break;default:o=JSON.stringify(n,null,2)}i(o)}},wa=Yt(),Cs=i=>{let e=new Map;return{logger:i,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let o=Date.now()-n;return e.delete(t),o},getCurrentTime:()=>Date.now()}};var lt=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,p=t(r),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,c;if("forward"in o&&typeof o.forward=="function")c=await o.forward(a,p,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:c}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}},Co=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,p=t(r),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,c;if("forward"in o&&typeof o.forward=="function")c=await o.forward(a,p,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:c}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}};var Xt=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new at;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,o){let r={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let p=this.getStepType(l,a),u=this.getStepMetadata(l,a),c=Object.keys(r);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...r}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{r=await l(r,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,f=Object.keys(r).filter(A=>!c.includes(A)),I;if(p==="execute"&&u.nodeName&&f.length>0){let A=`${u.nodeName}Result`;I=r[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:u.nodeName,executionTime:g,state:{...r},newFields:f,result:I})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:p,nodeName:u.nodeName,state:{...r}}),m}}return{finalState:r,stepsExecuted:s}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let o=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(o)return{nodeName:o.nodeName,dependencies:o.dependencies,produces:o.produces};let r=e.toString();return{nodeName:this.extractNodeNameFromSource(r),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return nt().input("userInput",nt.string("User input to the flow")).output("flowOutput",nt.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(c=>t.add(c)),u.dependencies.forEach(c=>n.add(c));let o=new Set;for(let u of Array.from(n))t.has(u)||o.add(u);let r=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(u=>{u.startsWith("_")||r.add(u)}),s.type==="merge"&&s.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(c=>r.add(c))}else for(let u of Array.from(t)){let c=!1;for(let d of e.steps)if(d.dependencies.includes(u)){c=!0;break}if(!c)if(u.endsWith("Result")){let d=u.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let h=m.getSignature().getOutputFields();for(let f of h)r.add(f.name)}else r.add(u)}else r.add(u)}if(o.size===0&&r.size===0){let u=[],c=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let f of h.getInputFields()){let I=this.toCamelCase(`${m}_${f.name}`);u.push({name:I,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of h.getOutputFields()){let I=this.toCamelCase(`${m}_${f.name}`);c.push({name:I,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let d=new D;return u.length>0?d.setInputFields(u):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),c.length>0?d.setOutputFields(c):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new D,l=[];for(let u of Array.from(o))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let p=[];for(let u of Array.from(r))u.startsWith("_")||p.push({name:u,type:{name:"string"},description:`Output field: ${u}`});return p.length===0&&p.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(p),a}constructor(e){i._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),i._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=Yt():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Cs(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new i(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new pe(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Ze(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=Ze(n);return e}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let o=Date.now();this.timingLogger?.startTiming("flow-execution");let r={};try{this.resetUsage(),this.resetTraces();let s;if(Array.isArray(t)){let g=t.filter(h=>h.role==="user").pop();if(!g)throw new Error("No user message found in values array");s=g.values}else s=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),r={...s},this.flowLogger){let g=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:o,inputFields:Object.keys(s),totalSteps:g.totalSteps,parallelGroups:g.parallelGroups,maxParallelism:g.maxParallelism,autoParallelEnabled:g.autoParallelEnabled})}let a=n?.tracer??this.defaultAIOptions?.tracer,l=n?.traceContext,p,u=l;if(a){let g=this.getExecutionPlan(),h=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=a.startSpan(h,{kind:va.INTERNAL,attributes:{total_steps:g.totalSteps,parallel_groups:g.parallelGroups,max_parallelism:g.maxParallelism,auto_parallel_enabled:g.autoParallelEnabled}});let f=l??Sa.active();u=Oa.setSpan(f,p)}let c={mainAi:e,mainOptions:(()=>{let g={...this.defaultAIOptions??{},...n};return n?.model&&(g.model=String(n.model)),a&&(g.tracer=a),u&&(g.traceContext=u),Object.keys(g).length>0?g:void 0})()},d=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,m=0;if(d){this.executionPlanner.setInitialFields(Object.keys(s));let g=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),h=await this.executeStepsWithLogging(g,r,c,!0);r=h.finalState,m=h.stepsExecuted}else{let g=await this.executeStepsWithLogging(this.flowDefinition,r,c,!1);r=g.finalState,m=g.stepsExecuted}if(this.flowLogger){let g=this.timingLogger?.endTiming("flow-execution")??Date.now()-o;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:g,finalState:r,outputFields:Object.keys(r),stepsExecuted:m})}return p&&p.end(),r}catch(s){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:s instanceof Error?s.message:String(s),state:r}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),s}}node(e,t){if(typeof t=="string"||t instanceof D){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let o=Ae(n);this.nodeGenerators.set(e,o),this.ensureProgram(),this.program.register(o)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],o=async r=>(await xe(n,async(l,p)=>{let u=l(r);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,p)=>({...l,...p}),r);if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"parallel-map",n)}else{let n=async o=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let r=e(o);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let o=e(n);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);let r=async(s,a)=>{let l=n?.ai??a.mainAi,p={...a.mainOptions??{},...n?.options??{}},u=t(s),c=p?.traceLabel?`Node:${e} (${p.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function"){if(d=await o.forward(l,u,{...p,traceLabel:c}),"getUsage"in o&&typeof o.getUsage=="function"){let m=o.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in o&&typeof o.getTraces=="function"){let m=o.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,o)=>{let r=e.predicate(n),s=e.branches.get(r);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:r,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,o);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,o)=>{let r=await xe(e,async(s,a)=>{let l=new lt(this.nodeGenerators);return await s(l).executeSteps(n,o)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:r}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,o)=>{let r=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=o(...a),p={...s};return delete p._parallelResults,p[n]=l,p};return this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:o}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let o=this.stepLabels.get(t),r=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,p=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&p<n;){p++,l={...l,[u]:p};for(let c=o;c<r;c++){let d=this.flowDefinition[c];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let o=Object.assign(r=>r,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(o),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,o=t._maxIterations,r=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,p=0;for(;n(l)&&p<o;){p++;for(let u of r)l=await u(l,a)}if(p>=o&&n(l))throw new Error(`While loop exceeded maximum iterations (${o}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,o){let r=async s=>{let a=s[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let p=o?.batchSize||this.autoParallelConfig.batchSize;l=await xe(a,async(u,c)=>n(u,c,s),p)}else l=a.map((p,u)=>n(p,u,s));else l=n(a,void 0,s);return{...s,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:o?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let r=typeof t=="string"?D.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)r=r.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)r=r.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)r=r.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)r=r.appendOutputField(s.name,s.type);return this.node(e,r)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let o=e(n);return{...n,...o}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function wo(i){return Xt.create(i)}var So=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let r=t.map(p=>`${p.hostPath}:${p.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:r},Labels:{}};o&&(s.Labels["com.example.tag"]=o);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===o);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),p=s[l];if(p)return await this.connectToContainer(p.Id),{Id:p.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:o})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let o=[],r=await this.listContainers(!0),s=e?r.filter(a=>a.Labels["com.example.tag"]===e):r;for(let a of s){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"removed"})}}return o}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(console.log("Executing command:",e),!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let o=await n.json(),r=await this.fetchDockerAPI(`/exec/${o.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!r.ok)throw new Error(`Failed to start exec instance: ${r.statusText}`);return await r.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(r=>setTimeout(r,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var vo=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let o=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!o)throw new Error("Failed to embed text");return this.func.length===2?this.func(o,t):this.func(o)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Oo=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(r=>r.name===t.name),o=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:o,func:async r=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:r});return s}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((s,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),o=await Promise.race([t,n]),{result:r}=o;if(typeof r!="object"||r===null||Object.keys(r).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(r)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=q(),o={jsonrpc:"2.0",id:n,method:e,params:t},r=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(o).then(p=>{if(this.activeRequests.delete(n),p!==null&&typeof p=="object"&&"error"in p){let u=p;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else p!==null&&typeof p=="object"&&"result"in p?a({result:p.result}):l(new Error("Invalid response no result or error"))}).catch(p=>{this.activeRequests.delete(n),l(p)})}),{result:s}=await r;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:o}=this.options;if(o){let r={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(r)}await this.transport.sendNotification(n)}};var Mo=class{endpoint=null;sseUrl;eventSource;constructor(e){this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let r=JSON.parse(n.data);if(!r.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=r.uri,e()}catch(o){t(o)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}},ko=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers},t?.authorization&&(this.customHeaders.Authorization=t.authorization)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),o=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(o.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=r=>{try{let s=JSON.parse(r.data);this.messageHandler&&this.messageHandler(s)}catch(s){console.error("Failed to parse SSE message:",s)}},this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),o=new TextDecoder,r="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}r+=o.decode(l,{stream:!0});let p=r.split(`
419
- `);r=p.pop()||"";for(let u of p)if(u.startsWith("data: ")){let c=u.slice(6);if(c==="[DONE]")return;try{let d=JSON.parse(c);this.messageHandler&&this.messageHandler(d)}catch(d){console.error("Failed to parse SSE data:",d)}}await s()}catch(a){throw n.releaseLock(),a}};await s()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);let o=n.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let r=n.headers.get("Content-Type");if(r?.includes("text/event-stream"))return this.handleSSEResponse(n,e.id);if(r?.includes("application/json"))return n.json();throw new Error(`Unexpected content type: ${r}`)}async handleSSEResponse(e,t){return new Promise((n,o)=>{let r=e.body?.getReader();if(!r){o(new Error("No response body reader available"));return}let s=new TextDecoder,a="",l=async()=>{try{let{done:p,value:u}=await r.read();if(p){r.releaseLock();return}a+=s.decode(u,{stream:!0});let c=a.split(`
420
- `);a=c.pop()||"";for(let d of c)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(p){r.releaseLock(),o(p)}};l().catch(o)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);n.status!==202&&console.warn(`Unexpected status for notification: ${n.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};function Ma(i,e,t,n,o){let r={...i};if(r.parameters){let s=r.parameters.properties?Object.keys(r.parameters.properties):[],l=t.filter(p=>s.includes(p)).filter(p=>p!=="model").filter(p=>!o.excludeFieldsFromPassthrough.includes(p));if(l.length>0){r.parameters=Ea(r.parameters,l);let p=r.func;r.func=async(u,c)=>{let d={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(d=vs(g.values,l))}else d=vs(e,l);let m={...u,...d};return await p(m,c)}}return r}return n&&!o.disableSmartModelRouting&&o.canConfigureSmartModelRouting&&(r.parameters=Os(r.parameters,n)),r}var ws=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),Ss=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),Zt=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:o,signature:r,agents:s,functions:a},l){let{disableSmartModelRouting:p,excludeFieldsFromPassthrough:u,debug:c}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=p,this.excludeFieldsFromPassthrough=u??[],this.debug=c,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw ws;if(o&&o.length<100)throw Ss;this.program=new H(r,{...l,description:o??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:ka(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=Os(this.func.parameters,d))}static create(e,t){let n=D.create(e),{ai:o,name:r,description:s,definition:a,agents:l,functions:p,...u}=t;return new i({ai:o,name:r,description:s,definition:a,signature:n,agents:l,functions:p},u)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,o)=>{let{model:r,...s}=n,a=this.ai??o?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...o,model:r}),u=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=u.find(g=>g.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
421
- `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let o=this.ai??e,r=o?.getModelList(),a=this.program.getSignature().getInputFields().map(c=>c.name),l=this.getDebug(o,n),p=this.agents?.map(c=>{let d=c.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return Ma(c.getFunction(),t,a,r,m)}),u=[...n?.functions??this.functions??[],...p??[]];return{ai:o,functions:u,debug:l}}async forward(e,t,n){let{ai:o,functions:r,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:r};return await this.program.forward(o,t,a)}async*streamingForward(e,t,n){let{ai:o,functions:r,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:r};return yield*this.program.streamingForward(o,t,a)}setDescription(e){if(!e||e.length<20)throw ws;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw Ss;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function ka(i){return i.split(/[^a-zA-Z0-9]/).map((n,o)=>{let r=n.toLowerCase();return o>0&&r&&r[0]?r[0].toUpperCase()+r.slice(1):r}).join("")}function Os(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(s=>s.key),description:`The AI model to use for this function call. Available options: ${e.map(s=>`\`${s.key}\` ${s.description}`).join(", ")}`},o={...t.properties??{},model:n},r=[...t.required??[],"model"];return{...t,properties:o,required:r}}function Ea(i,e){let t=structuredClone(i);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(o=>!e.includes(o));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function vs(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Pa(i,e){let t=typeof i=="string"?D.create(i):i,{ai:n,name:o,description:r,definition:s,agents:a,functions:l,...p}=e;return new Zt({ai:n,name:o,description:r,definition:s,signature:t,agents:a,functions:l},p)}var Fa=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,o=e?.maxIterations??2,r=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return wo({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:o,qualityTarget:r,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,p=await i(l);return{...a,retrievalResult:{retrievedDocument:p,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],p=l.length>0?await Promise.all(l.filter(Boolean).map(u=>i(u))):[];return{...a,retrievalResults:p}}).execute("evidenceSynthesizer",a=>{let l=[...a.allEvidence||[],...a.retrievalResults||[]].filter(Boolean);return{collectedEvidence:l.length>0?l:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...a.allEvidence,...a.retrievalResults],evidenceSources:[...a.evidenceSources,`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:a.accumulatedContext||a.synthesizedEvidence||a.allEvidence.join(`
422
- `),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],p=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,u=await i(p);return{...a,healingResult:{healingDocument:u}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};export{Pt as AxAI,we as AxAIAnthropic,ht as AxAIAnthropicModel,un as AxAIAnthropicVertexModel,ke as AxAIAzureOpenAI,Ee as AxAICohere,It as AxAICohereEmbedModel,yt as AxAICohereModel,Pe as AxAIDeepSeek,bt as AxAIDeepSeekModel,Fe as AxAIGoogleGemini,Rn as AxAIGoogleGeminiEmbedModel,vr as AxAIGoogleGeminiEmbedTypes,Tt as AxAIGoogleGeminiModel,Cn as AxAIGoogleGeminiSafetyCategory,wn as AxAIGoogleGeminiSafetyThreshold,He as AxAIGrok,Nr as AxAIGrokEmbedModels,Et as AxAIGrokModel,De as AxAIGroq,Rt as AxAIGroqModel,Le as AxAIHuggingFace,En as AxAIHuggingFaceModel,Ne as AxAIMistral,Er as AxAIMistralEmbedModels,Ct as AxAIMistralModel,$e as AxAIOllama,Me as AxAIOpenAI,F as AxAIOpenAIBase,Se as AxAIOpenAIEmbedModel,xt as AxAIOpenAIModel,Ue as AxAIOpenAIResponses,St as AxAIOpenAIResponsesBase,Ge as AxAIOpenAIResponsesImpl,ve as AxAIOpenAIResponsesModel,Be as AxAIOpenRouter,E as AxAIRefusalError,qe as AxAIReka,Ot as AxAIRekaModel,Te as AxAIServiceAbortedError,se as AxAIServiceAuthenticationError,j as AxAIServiceError,oe as AxAIServiceNetworkError,re as AxAIServiceResponseError,de as AxAIServiceStatusError,Z as AxAIServiceStreamTerminatedError,me as AxAIServiceTimeoutError,ze as AxAITogether,je as AxAIWebLLM,kt as AxAIWebLLMModel,Zt as AxAgent,xo as AxApacheTika,ae as AxAssertionError,An as AxBalancer,_ as AxBaseAI,ce as AxBaseOptimizer,st as AxBootstrapFewShot,ee as AxContentProcessingError,Jn as AxDB,Q as AxDBBase,Ke as AxDBCloudflare,Yn as AxDBManager,ie as AxDBMemory,We as AxDBPinecone,Ve as AxDBWeaviate,Jt as AxDefaultCostTracker,Ao as AxDefaultResultReranker,So as AxDockerSession,vo as AxEmbeddingAdapter,ra as AxEvalUtil,Xt as AxFlow,it as AxFlowDependencyAnalyzer,at as AxFlowExecutionPlanner,lt as AxFlowSubContextImpl,Co as AxFlowTypedSubContextImpl,G as AxFluentFieldType,Nt as AxFunctionError,$t as AxFunctionProcessor,H as AxGen,Ht as AxGenerateError,To as AxHFDataLoader,tt as AxInstanceRegistry,Uo as AxLLMRequestTypeValues,Oo as AxMCPClient,Mo as AxMCPHTTPSSETransport,ko as AxMCPStreambleHTTPTransport,V as AxMediaNotSupportedError,Qe as AxMemory,Ro as AxMiPRO,Dn as AxMockAIService,Ln as AxMultiServiceRouter,rt as AxOptimizedProgramImpl,pe as AxProgram,fe as AxPromptTemplate,Bn as AxProviderRouter,_e as AxRateLimiterTokenUsage,D as AxSignature,Bt as AxSignatureBuilder,Io as AxSimpleClassifier,yo as AxSimpleClassifierClass,Bo as AxSpanKindValues,fo as AxStringUtil,bo as AxTestPrompt,Pa as agent,hi as ai,Ae as ax,Ir as axAIAnthropicDefaultConfig,$s as axAIAnthropicVertexDefaultConfig,Hs as axAIAzureOpenAIBestConfig,zs as axAIAzureOpenAICreativeConfig,Tr as axAIAzureOpenAIDefaultConfig,js as axAIAzureOpenAIFastConfig,Qs as axAICohereCreativeConfig,wr as axAICohereDefaultConfig,Xs as axAIDeepSeekCodeConfig,Sr as axAIDeepSeekDefaultConfig,Mr as axAIGoogleGeminiDefaultConfig,Zs as axAIGoogleGeminiDefaultCreativeConfig,gi as axAIGrokBestConfig,Kn as axAIGrokDefaultConfig,ni as axAIHuggingFaceCreativeConfig,kr as axAIHuggingFaceDefaultConfig,oi as axAIMistralBestConfig,_n as axAIMistralDefaultConfig,Pr as axAIOllamaDefaultConfig,ri as axAIOllamaDefaultCreativeConfig,gn as axAIOpenAIBestConfig,hn as axAIOpenAICreativeConfig,ge as axAIOpenAIDefaultConfig,fn as axAIOpenAIFastConfig,ii as axAIOpenAIResponsesBestConfig,ai as axAIOpenAIResponsesCreativeConfig,vt as axAIOpenAIResponsesDefaultConfig,Fr as axAIOpenRouterDefaultConfig,pi as axAIRekaBestConfig,ui as axAIRekaCreativeConfig,Mt as axAIRekaDefaultConfig,ci as axAIRekaFastConfig,Dr as axAITogetherDefaultConfig,mi as axAIWebLLMCreativeConfig,Lr as axAIWebLLMDefaultConfig,li as axAnalyzeChatPromptRequirements,he as axAnalyzeRequestRequirements,O as axBaseAIDefaultConfig,L as axBaseAIDefaultCreativeConfig,Ii as axCheckMetricsHealth,$o as axCreateDefaultColorLogger,bs as axCreateDefaultOptimizerColorLogger,sa as axCreateDefaultOptimizerTextLogger,_s as axCreateDefaultTextLogger,Yt as axCreateFlowColorLogger,Ca as axCreateFlowTextLogger,wa as axDefaultFlowLogger,$r as axDefaultMetricsConfig,Kt as axDefaultOptimizerLogger,Ts as axDefaultOptimizerMetricsConfig,Ws as axGetCompatibilityReport,Js as axGetFormatCompatibility,Ri as axGetMetricsConfig,la as axGetOptimizerMetricsConfig,Vs as axGetProvidersWithMediaSupport,M as axGlobals,ft as axModelInfoAnthropic,In as axModelInfoCohere,Tn as axModelInfoDeepSeek,Sn as axModelInfoGoogleGemini,Hn as axModelInfoGrok,Mn as axModelInfoGroq,kn as axModelInfoHuggingFace,Fn as axModelInfoMistral,Oe as axModelInfoOpenAI,dn as axModelInfoOpenAIResponses,Gn as axModelInfoReka,qn as axModelInfoTogether,zn as axModelInfoWebLLM,$n as axProcessContentForProvider,Fa as axRAG,xn as axScoreProvidersForRequest,yn as axSelectOptimalProvider,S as axSpanAttributes,te as axSpanEvents,Ti as axUpdateMetricsConfig,aa as axUpdateOptimizerMetricsConfig,Ce as axValidateChatRequestMessage,pn as axValidateChatResponseResult,Rr as axValidateProviderCapabilities,nt as f,wo as flow,Ra as s};
417
+ `;break;default:o=JSON.stringify(n,null,2)}i(o)}},Ca=Yt(),Rs=i=>{let e=new Map;return{logger:i,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let o=Date.now()-n;return e.delete(t),o},getCurrentTime:()=>Date.now()}};var lt=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,p=t(r),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,p,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}},Co=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,p=t(r),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,p,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}};var Xt=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new at;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,o){let r={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let p=this.getStepType(l,a),u=this.getStepMetadata(l,a),d=Object.keys(r);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...r}});let c=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{r=await l(r,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-c,x=Object.keys(r).filter(A=>!d.includes(A)),f;if(p==="execute"&&u.nodeName&&x.length>0){let A=`${u.nodeName}Result`;f=r[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:p,nodeName:u.nodeName,executionTime:g,state:{...r},newFields:x,result:f})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:p,nodeName:u.nodeName,state:{...r}}),m}}return{finalState:r,stepsExecuted:s}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let o=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(o)return{nodeName:o.nodeName,dependencies:o.dependencies,produces:o.produces};let r=e.toString();return{nodeName:this.extractNodeNameFromSource(r),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return nt().input("userInput",nt.string("User input to the flow")).output("flowOutput",nt.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(d=>t.add(d)),u.dependencies.forEach(d=>n.add(d));let o=new Set;for(let u of Array.from(n))t.has(u)||o.add(u);let r=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(u=>{u.startsWith("_")||r.add(u)}),s.type==="merge"&&s.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(d=>r.add(d))}else for(let u of Array.from(t)){let d=!1;for(let c of e.steps)if(c.dependencies.includes(u)){d=!0;break}if(!d)if(u.endsWith("Result")){let c=u.replace("Result",""),m=this.nodeGenerators.get(c);if(m){let h=m.getSignature().getOutputFields();for(let x of h)r.add(x.name)}else r.add(u)}else r.add(u)}if(o.size===0&&r.size===0){let u=[],d=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let x of h.getInputFields()){let f=this.toCamelCase(`${m}_${x.name}`);u.push({name:f,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}for(let x of h.getOutputFields()){let f=this.toCamelCase(`${m}_${x.name}`);d.push({name:f,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}}let c=new L;return u.length>0?c.setInputFields(u):c.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),d.length>0?c.setOutputFields(d):c.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),c}let a=new L,l=[];for(let u of Array.from(o))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let p=[];for(let u of Array.from(r))u.startsWith("_")||p.push({name:u,type:{name:"string"},description:`Output field: ${u}`});return p.length===0&&p.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(p),a}constructor(e){i._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),i._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=Yt():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Rs(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new i(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new pe(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Ze(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=Ze(n);return e}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let o=Date.now();this.timingLogger?.startTiming("flow-execution");let r={};try{this.resetUsage(),this.resetTraces();let s;if(Array.isArray(t)){let g=t.filter(h=>h.role==="user").pop();if(!g)throw new Error("No user message found in values array");s=g.values}else s=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),r={...s},this.flowLogger){let g=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:o,inputFields:Object.keys(s),totalSteps:g.totalSteps,parallelGroups:g.parallelGroups,maxParallelism:g.maxParallelism,autoParallelEnabled:g.autoParallelEnabled})}let a=n?.tracer??this.defaultAIOptions?.tracer,l=n?.traceContext,p,u=l;if(a){let g=this.getExecutionPlan(),h=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=a.startSpan(h,{kind:Sa.INTERNAL,attributes:{total_steps:g.totalSteps,parallel_groups:g.parallelGroups,max_parallelism:g.maxParallelism,auto_parallel_enabled:g.autoParallelEnabled}});let x=l??wa.active();u=va.setSpan(x,p)}let d={mainAi:e,mainOptions:(()=>{let g={...this.defaultAIOptions??{},...n};return n?.model&&(g.model=String(n.model)),a&&(g.tracer=a),u&&(g.traceContext=u),Object.keys(g).length>0?g:void 0})()},c=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,m=0;if(c){this.executionPlanner.setInitialFields(Object.keys(s));let g=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),h=await this.executeStepsWithLogging(g,r,d,!0);r=h.finalState,m=h.stepsExecuted}else{let g=await this.executeStepsWithLogging(this.flowDefinition,r,d,!1);r=g.finalState,m=g.stepsExecuted}if(this.flowLogger){let g=this.timingLogger?.endTiming("flow-execution")??Date.now()-o;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:g,finalState:r,outputFields:Object.keys(r),stepsExecuted:m})}return p&&p.end(),r}catch(s){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:s instanceof Error?s.message:String(s),state:r}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),s}}node(e,t){if(typeof t=="string"||t instanceof L){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let o=Ae(n);this.nodeGenerators.set(e,o),this.ensureProgram(),this.program.register(o)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],o=async r=>(await xe(n,async(l,p)=>{let u=l(r);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,p)=>({...l,...p}),r);if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"parallel-map",n)}else{let n=async o=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let r=e(o);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let o=e(n);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);let r=async(s,a)=>{let l=n?.ai??a.mainAi,p={...a.mainOptions??{},...n?.options??{}},u=t(s),d=p?.traceLabel?`Node:${e} (${p.traceLabel})`:`Node:${e}`,c;if("forward"in o&&typeof o.forward=="function"){if(c=await o.forward(l,u,{...p,traceLabel:d}),"getUsage"in o&&typeof o.getUsage=="function"){let m=o.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in o&&typeof o.getTraces=="function"){let m=o.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:c}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,o)=>{let r=e.predicate(n),s=e.branches.get(r);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:r,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,o);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,o)=>{let r=await xe(e,async(s,a)=>{let l=new lt(this.nodeGenerators);return await s(l).executeSteps(n,o)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:r}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,o)=>{let r=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=o(...a),p={...s};return delete p._parallelResults,p[n]=l,p};return this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:o}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let o=this.stepLabels.get(t),r=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,p=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&p<n;){p++,l={...l,[u]:p};for(let d=o;d<r;d++){let c=this.flowDefinition[d];c&&(l=await c(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let o=Object.assign(r=>r,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(o),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,o=t._maxIterations,r=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,p=0;for(;n(l)&&p<o;){p++;for(let u of r)l=await u(l,a)}if(p>=o&&n(l))throw new Error(`While loop exceeded maximum iterations (${o}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,o){let r=async s=>{let a=s[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let p=o?.batchSize||this.autoParallelConfig.batchSize;l=await xe(a,async(u,d)=>n(u,d,s),p)}else l=a.map((p,u)=>n(p,u,s));else l=n(a,void 0,s);return{...s,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:o?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let r=typeof t=="string"?L.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)r=r.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)r=r.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)r=r.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)r=r.appendOutputField(s.name,s.type);return this.node(e,r)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let o=e(n);return{...n,...o}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function wo(i){return Xt.create(i)}var So=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let r=t.map(p=>`${p.hostPath}:${p.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:r},Labels:{}};o&&(s.Labels["com.example.tag"]=o);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:o}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===o);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),p=s[l];if(p)return await this.connectToContainer(p.Id),{Id:p.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:o})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let o=[],r=await this.listContainers(!0),s=e?r.filter(a=>a.Labels["com.example.tag"]===e):r;for(let a of s){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}o.push({Id:a.Id,Action:"removed"})}}return o}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let o=await n.json(),r=await this.fetchDockerAPI(`/exec/${o.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!r.ok)throw new Error(`Failed to start exec instance: ${r.statusText}`);return await r.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(r=>setTimeout(r,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var vo=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let o=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!o)throw new Error("Failed to embed text");return this.func.length===2?this.func(o,t):this.func(o)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Oo=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(r=>r.name===t.name),o=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:o,func:async r=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:r});return s}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((s,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),o=await Promise.race([t,n]),{result:r}=o;if(typeof r!="object"||r===null||Object.keys(r).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(r)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=B(),o={jsonrpc:"2.0",id:n,method:e,params:t},r=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(o).then(p=>{if(this.activeRequests.delete(n),p!==null&&typeof p=="object"&&"error"in p){let u=p;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else p!==null&&typeof p=="object"&&"result"in p?a({result:p.result}):l(new Error("Invalid response no result or error"))}).catch(p=>{this.activeRequests.delete(n),l(p)})}),{result:s}=await r;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:o}=this.options;if(o){let r={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(r)}await this.transport.sendNotification(n)}};var Mo=class{endpoint=null;sseUrl;eventSource;constructor(e){this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let r=JSON.parse(n.data);if(!r.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=r.uri,e()}catch(o){t(o)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}},ko=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers},t?.authorization&&(this.customHeaders.Authorization=t.authorization)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),o=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(o.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=r=>{try{let s=JSON.parse(r.data);this.messageHandler&&this.messageHandler(s)}catch(s){console.error("Failed to parse SSE message:",s)}},this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),o=new TextDecoder,r="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}r+=o.decode(l,{stream:!0});let p=r.split(`
418
+ `);r=p.pop()||"";for(let u of p)if(u.startsWith("data: ")){let d=u.slice(6);if(d==="[DONE]")return;try{let c=JSON.parse(d);this.messageHandler&&this.messageHandler(c)}catch(c){console.error("Failed to parse SSE data:",c)}}await s()}catch(a){throw n.releaseLock(),a}};await s()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);let o=n.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let r=n.headers.get("Content-Type");if(r?.includes("text/event-stream"))return this.handleSSEResponse(n,e.id);if(r?.includes("application/json"))return n.json();throw new Error(`Unexpected content type: ${r}`)}async handleSSEResponse(e,t){return new Promise((n,o)=>{let r=e.body?.getReader();if(!r){o(new Error("No response body reader available"));return}let s=new TextDecoder,a="",l=async()=>{try{let{done:p,value:u}=await r.read();if(p){r.releaseLock();return}a+=s.decode(u,{stream:!0});let d=a.split(`
419
+ `);a=d.pop()||"";for(let c of d)if(c.startsWith("data: ")){let m=c.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(p){r.releaseLock(),o(p)}};l().catch(o)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);n.status!==202&&console.warn(`Unexpected status for notification: ${n.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};function Oa(i,e,t,n,o){let r={...i};if(r.parameters){let s=r.parameters.properties?Object.keys(r.parameters.properties):[],l=t.filter(p=>s.includes(p)).filter(p=>p!=="model").filter(p=>!o.excludeFieldsFromPassthrough.includes(p));if(l.length>0){r.parameters=ka(r.parameters,l);let p=r.func;r.func=async(u,d)=>{let c={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(c=Ss(g.values,l))}else c=Ss(e,l);let m={...u,...c};return await p(m,d)}}return r}return n&&!o.disableSmartModelRouting&&o.canConfigureSmartModelRouting&&(r.parameters=vs(r.parameters,n)),r}var Cs=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),ws=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),Zt=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:o,signature:r,agents:s,functions:a},l){let{disableSmartModelRouting:p,excludeFieldsFromPassthrough:u,debug:d}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=p,this.excludeFieldsFromPassthrough=u??[],this.debug=d,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw Cs;if(o&&o.length<100)throw ws;this.program=new H(r,{...l,description:o??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:Ma(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let c=e?.getModelList();c&&!this.disableSmartModelRouting&&(this.func.parameters=vs(this.func.parameters,c))}static create(e,t){let n=L.create(e),{ai:o,name:r,description:s,definition:a,agents:l,functions:p,...u}=t;return new i({ai:o,name:r,description:s,definition:a,signature:n,agents:l,functions:p},u)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,o)=>{let{model:r,...s}=n,a=this.ai??o?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...o,model:r}),u=this.program.getSignature().getOutputFields();return Object.keys(l).map(c=>{let m=u.find(g=>g.name===c);return m?`${m.title}: ${l[c]}`:`${c}: ${l[c]}`}).join(`
420
+ `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let o=this.ai??e,r=o?.getModelList(),a=this.program.getSignature().getInputFields().map(d=>d.name),l=this.getDebug(o,n),p=this.agents?.map(d=>{let c=d.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:c.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:c.canConfigureSmartModelRouting};return Oa(d.getFunction(),t,a,r,m)}),u=[...n?.functions??this.functions??[],...p??[]];return{ai:o,functions:u,debug:l}}async forward(e,t,n){let{ai:o,functions:r,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:r};return await this.program.forward(o,t,a)}async*streamingForward(e,t,n){let{ai:o,functions:r,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:r};return yield*this.program.streamingForward(o,t,a)}setDescription(e){if(!e||e.length<20)throw Cs;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw ws;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function Ma(i){return i.split(/[^a-zA-Z0-9]/).map((n,o)=>{let r=n.toLowerCase();return o>0&&r&&r[0]?r[0].toUpperCase()+r.slice(1):r}).join("")}function vs(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(s=>s.key),description:`The AI model to use for this function call. Available options: ${e.map(s=>`\`${s.key}\` ${s.description}`).join(", ")}`},o={...t.properties??{},model:n},r=[...t.required??[],"model"];return{...t,properties:o,required:r}}function ka(i,e){let t=structuredClone(i);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(o=>!e.includes(o));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Ss(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Ea(i,e){let t=typeof i=="string"?L.create(i):i,{ai:n,name:o,description:r,definition:s,agents:a,functions:l,...p}=e;return new Zt({ai:n,name:o,description:r,definition:s,signature:t,agents:a,functions:l},p)}var Pa=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,o=e?.maxIterations??2,r=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return wo({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:o,qualityTarget:r,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,p=await i(l);return{...a,retrievalResult:{retrievedDocument:p,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],p=l.length>0?await Promise.all(l.filter(Boolean).map(u=>i(u))):[];return{...a,retrievalResults:p}}).execute("evidenceSynthesizer",a=>{let l=[...a.allEvidence||[],...a.retrievalResults||[]].filter(Boolean);return{collectedEvidence:l.length>0?l:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...a.allEvidence,...a.retrievalResults],evidenceSources:[...a.evidenceSources,`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:a.accumulatedContext||a.synthesizedEvidence||a.allEvidence.join(`
421
+ `),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],p=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,u=await i(p);return{...a,healingResult:{healingDocument:u}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};export{Pt as AxAI,we as AxAIAnthropic,ht as AxAIAnthropicModel,un as AxAIAnthropicVertexModel,ke as AxAIAzureOpenAI,Ee as AxAICohere,It as AxAICohereEmbedModel,yt as AxAICohereModel,Pe as AxAIDeepSeek,bt as AxAIDeepSeekModel,Fe as AxAIGoogleGemini,Rn as AxAIGoogleGeminiEmbedModel,vr as AxAIGoogleGeminiEmbedTypes,Tt as AxAIGoogleGeminiModel,Cn as AxAIGoogleGeminiSafetyCategory,wn as AxAIGoogleGeminiSafetyThreshold,He as AxAIGrok,Nr as AxAIGrokEmbedModels,Et as AxAIGrokModel,De as AxAIGroq,Rt as AxAIGroqModel,Le as AxAIHuggingFace,En as AxAIHuggingFaceModel,Ne as AxAIMistral,Er as AxAIMistralEmbedModels,Ct as AxAIMistralModel,Ge as AxAIOllama,Me as AxAIOpenAI,_ as AxAIOpenAIBase,Se as AxAIOpenAIEmbedModel,xt as AxAIOpenAIModel,Ue as AxAIOpenAIResponses,St as AxAIOpenAIResponsesBase,$e as AxAIOpenAIResponsesImpl,ve as AxAIOpenAIResponsesModel,Be as AxAIOpenRouter,E as AxAIRefusalError,qe as AxAIReka,Ot as AxAIRekaModel,Te as AxAIServiceAbortedError,se as AxAIServiceAuthenticationError,j as AxAIServiceError,oe as AxAIServiceNetworkError,re as AxAIServiceResponseError,de as AxAIServiceStatusError,Z as AxAIServiceStreamTerminatedError,me as AxAIServiceTimeoutError,ze as AxAITogether,je as AxAIWebLLM,kt as AxAIWebLLMModel,Zt as AxAgent,xo as AxApacheTika,ae as AxAssertionError,An as AxBalancer,D as AxBaseAI,ce as AxBaseOptimizer,st as AxBootstrapFewShot,ee as AxContentProcessingError,Jn as AxDB,Q as AxDBBase,Ke as AxDBCloudflare,Yn as AxDBManager,ie as AxDBMemory,We as AxDBPinecone,Ve as AxDBWeaviate,Jt as AxDefaultCostTracker,Ao as AxDefaultResultReranker,So as AxDockerSession,vo as AxEmbeddingAdapter,oa as AxEvalUtil,Xt as AxFlow,it as AxFlowDependencyAnalyzer,at as AxFlowExecutionPlanner,lt as AxFlowSubContextImpl,Co as AxFlowTypedSubContextImpl,U as AxFluentFieldType,Nt as AxFunctionError,Gt as AxFunctionProcessor,H as AxGen,Ht as AxGenerateError,To as AxHFDataLoader,tt as AxInstanceRegistry,Uo as AxLLMRequestTypeValues,Oo as AxMCPClient,Mo as AxMCPHTTPSSETransport,ko as AxMCPStreambleHTTPTransport,V as AxMediaNotSupportedError,Qe as AxMemory,Ro as AxMiPRO,Dn as AxMockAIService,Ln as AxMultiServiceRouter,rt as AxOptimizedProgramImpl,pe as AxProgram,fe as AxPromptTemplate,Bn as AxProviderRouter,_e as AxRateLimiterTokenUsage,L as AxSignature,Bt as AxSignatureBuilder,Io as AxSimpleClassifier,yo as AxSimpleClassifierClass,Bo as AxSpanKindValues,fo as AxStringUtil,bo as AxTestPrompt,Ea as agent,gi as ai,Ae as ax,Ir as axAIAnthropicDefaultConfig,Ns as axAIAnthropicVertexDefaultConfig,js as axAIAzureOpenAIBestConfig,qs as axAIAzureOpenAICreativeConfig,Tr as axAIAzureOpenAIDefaultConfig,zs as axAIAzureOpenAIFastConfig,Js as axAICohereCreativeConfig,wr as axAICohereDefaultConfig,Ys as axAIDeepSeekCodeConfig,Sr as axAIDeepSeekDefaultConfig,Mr as axAIGoogleGeminiDefaultConfig,Xs as axAIGoogleGeminiDefaultCreativeConfig,mi as axAIGrokBestConfig,Kn as axAIGrokDefaultConfig,ti as axAIHuggingFaceCreativeConfig,kr as axAIHuggingFaceDefaultConfig,ni as axAIMistralBestConfig,_n as axAIMistralDefaultConfig,Pr as axAIOllamaDefaultConfig,oi as axAIOllamaDefaultCreativeConfig,gn as axAIOpenAIBestConfig,hn as axAIOpenAICreativeConfig,ge as axAIOpenAIDefaultConfig,fn as axAIOpenAIFastConfig,si as axAIOpenAIResponsesBestConfig,ii as axAIOpenAIResponsesCreativeConfig,vt as axAIOpenAIResponsesDefaultConfig,Fr as axAIOpenRouterDefaultConfig,li as axAIRekaBestConfig,pi as axAIRekaCreativeConfig,Mt as axAIRekaDefaultConfig,ui as axAIRekaFastConfig,Dr as axAITogetherDefaultConfig,di as axAIWebLLMCreativeConfig,Lr as axAIWebLLMDefaultConfig,ai as axAnalyzeChatPromptRequirements,he as axAnalyzeRequestRequirements,O as axBaseAIDefaultConfig,N as axBaseAIDefaultCreativeConfig,yi as axCheckMetricsHealth,Go as axCreateDefaultColorLogger,Is as axCreateDefaultOptimizerColorLogger,ra as axCreateDefaultOptimizerTextLogger,Fs as axCreateDefaultTextLogger,Yt as axCreateFlowColorLogger,Ra as axCreateFlowTextLogger,Ca as axDefaultFlowLogger,Gr as axDefaultMetricsConfig,Kt as axDefaultOptimizerLogger,bs as axDefaultOptimizerMetricsConfig,Ks as axGetCompatibilityReport,Vs as axGetFormatCompatibility,Ti as axGetMetricsConfig,aa as axGetOptimizerMetricsConfig,Ws as axGetProvidersWithMediaSupport,M as axGlobals,ft as axModelInfoAnthropic,In as axModelInfoCohere,Tn as axModelInfoDeepSeek,Sn as axModelInfoGoogleGemini,Hn as axModelInfoGrok,Mn as axModelInfoGroq,kn as axModelInfoHuggingFace,Fn as axModelInfoMistral,Oe as axModelInfoOpenAI,dn as axModelInfoOpenAIResponses,$n as axModelInfoReka,qn as axModelInfoTogether,zn as axModelInfoWebLLM,Gn as axProcessContentForProvider,Pa as axRAG,xn as axScoreProvidersForRequest,yn as axSelectOptimalProvider,v as axSpanAttributes,te as axSpanEvents,bi as axUpdateMetricsConfig,ia as axUpdateOptimizerMetricsConfig,Ce as axValidateChatRequestMessage,pn as axValidateChatResponseResult,Rr as axValidateProviderCapabilities,nt as f,wo as flow,Ta as s};
423
422
  //# sourceMappingURL=index.js.map