@ax-llm/ax 16.0.8 → 16.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +17 -17
- package/index.cjs.map +1 -1
- package/index.global.js +2 -2
- package/index.global.js.map +1 -1
- package/index.js +26 -26
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var Yl=Object.create;var yr=Object.defineProperty;var Xl=Object.getOwnPropertyDescriptor;var Zl=Object.getOwnPropertyNames;var ec=Object.getPrototypeOf,tc=Object.prototype.hasOwnProperty;var nc=(i,e)=>{for(var t in e)yr(i,t,{get:e[t],enumerable:!0})},pi=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zl(e))!tc.call(i,r)&&r!==t&&yr(i,r,{get:()=>e[r],enumerable:!(n=Xl(e,r))||n.enumerable});return i};var Pn=(i,e,t)=>(t=i!=null?Yl(ec(i)):{},pi(e||!i||!i.__esModule?yr(t,"default",{value:i,enumerable:!0}):t,i)),rc=i=>pi(yr({},"__esModule",{value:!0}),i);var $u={};nc($u,{AxACE:()=>
|
|
1
|
+
"use strict";var Yl=Object.create;var yr=Object.defineProperty;var Xl=Object.getOwnPropertyDescriptor;var Zl=Object.getOwnPropertyNames;var ec=Object.getPrototypeOf,tc=Object.prototype.hasOwnProperty;var nc=(i,e)=>{for(var t in e)yr(i,t,{get:e[t],enumerable:!0})},pi=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zl(e))!tc.call(i,r)&&r!==t&&yr(i,r,{get:()=>e[r],enumerable:!(n=Xl(e,r))||n.enumerable});return i};var Pn=(i,e,t)=>(t=i!=null?Yl(ec(i)):{},pi(e||!i||!i.__esModule?yr(t,"default",{value:i,enumerable:!0}):t,i)),rc=i=>pi(yr({},"__esModule",{value:!0}),i);var $u={};nc($u,{AxACE:()=>Do,AxACEOptimizedProgram:()=>dr,AxAI:()=>Yn,AxAIAnthropic:()=>Ut,AxAIAnthropicModel:()=>Nn,AxAIAnthropicVertexModel:()=>$n,AxAIAzureOpenAI:()=>Ht,AxAICohere:()=>Kt,AxAICohereEmbedModel:()=>Un,AxAICohereModel:()=>Gn,AxAIDeepSeek:()=>Wt,AxAIDeepSeekModel:()=>Bn,AxAIGoogleGemini:()=>Vt,AxAIGoogleGeminiEmbedModel:()=>$r,AxAIGoogleGeminiEmbedTypes:()=>ys,AxAIGoogleGeminiModel:()=>jn,AxAIGoogleGeminiSafetyCategory:()=>Lr,AxAIGoogleGeminiSafetyThreshold:()=>Dr,AxAIGrok:()=>an,AxAIGrokEmbedModels:()=>Ps,AxAIGrokModel:()=>Qn,AxAIGroq:()=>Qt,AxAIGroqModel:()=>qn,AxAIHuggingFace:()=>Yt,AxAIHuggingFaceModel:()=>qr,AxAIMistral:()=>Xt,AxAIMistralEmbedModels:()=>Rs,AxAIMistralModel:()=>zn,AxAIOllama:()=>Zt,AxAIOpenAI:()=>zt,AxAIOpenAIBase:()=>fe,AxAIOpenAIEmbedModel:()=>Bt,AxAIOpenAIModel:()=>Dn,AxAIOpenAIResponses:()=>tn,AxAIOpenAIResponsesBase:()=>Hn,AxAIOpenAIResponsesImpl:()=>en,AxAIOpenAIResponsesModel:()=>jt,AxAIOpenRouter:()=>nn,AxAIRefusalError:()=>de,AxAIReka:()=>rn,AxAIRekaModel:()=>Wn,AxAIServiceAbortedError:()=>Lt,AxAIServiceAuthenticationError:()=>ft,AxAIServiceError:()=>Oe,AxAIServiceNetworkError:()=>Ne,AxAIServiceResponseError:()=>ht,AxAIServiceStatusError:()=>qe,AxAIServiceStreamTerminatedError:()=>Ke,AxAIServiceTimeoutError:()=>tt,AxAITogether:()=>on,AxAIWebLLM:()=>sn,AxAIWebLLMModel:()=>Jn,AxAgent:()=>fr,AxApacheTika:()=>Oo,AxAssertionError:()=>ct,AxBalancer:()=>Er,AxBaseAI:()=>Ae,AxBaseOptimizer:()=>De,AxBootstrapFewShot:()=>Tn,AxContentProcessingError:()=>nt,AxDB:()=>ro,AxDBBase:()=>Ve,AxDBCloudflare:()=>ln,AxDBManager:()=>oo,AxDBMemory:()=>Ct,AxDBPinecone:()=>cn,AxDBWeaviate:()=>un,AxDefaultCostTracker:()=>lr,AxDefaultResultReranker:()=>vo,AxDockerSession:()=>zo,AxEmbeddingAdapter:()=>Ho,AxEvalUtil:()=>bl,AxFlow:()=>gr,AxFlowDependencyAnalyzer:()=>Cn,AxFlowExecutionPlanner:()=>wn,AxFlowSubContextImpl:()=>On,AxFlowTypedSubContextImpl:()=>jo,AxFluentFieldType:()=>Re,AxFunctionError:()=>er,AxFunctionProcessor:()=>nr,AxGEPA:()=>bn,AxGEPAFlow:()=>Go,AxGen:()=>xe,AxGenerateError:()=>ir,AxHFDataLoader:()=>Lo,AxInstanceRegistry:()=>gn,AxJudge:()=>An,AxLLMRequestTypeValues:()=>ns,AxLearn:()=>$o,AxMCPClient:()=>Ko,AxMCPHTTPSSETransport:()=>Jo,AxMCPStreambleHTTPTransport:()=>Vo,AxMediaNotSupportedError:()=>We,AxMemory:()=>pn,AxMiPRO:()=>Bo,AxMockAIService:()=>Kr,AxMultiServiceRouter:()=>Wr,AxOptimizedProgramImpl:()=>pt,AxProgram:()=>St,AxPromptTemplate:()=>Ft,AxProviderRouter:()=>Yr,AxRateLimiterTokenUsage:()=>Jt,AxSignature:()=>ge,AxSignatureBuilder:()=>or,AxSimpleClassifier:()=>Mo,AxSimpleClassifierClass:()=>ko,AxSpanKindValues:()=>rs,AxStopFunctionCallException:()=>Et,AxStringUtil:()=>So,AxSynth:()=>In,AxTestPrompt:()=>Eo,AxTokenLimitError:()=>Fn,AxTraceLogger:()=>yn,agent:()=>zl,ai:()=>Ta,ax:()=>Me,axAIAnthropicDefaultConfig:()=>ds,axAIAnthropicVertexDefaultConfig:()=>Qi,axAIAzureOpenAIBestConfig:()=>ea,axAIAzureOpenAICreativeConfig:()=>Xi,axAIAzureOpenAIDefaultConfig:()=>gs,axAIAzureOpenAIFastConfig:()=>Zi,axAICohereCreativeConfig:()=>sa,axAICohereDefaultConfig:()=>xs,axAIDeepSeekCodeConfig:()=>ia,axAIDeepSeekDefaultConfig:()=>As,axAIGoogleGeminiDefaultConfig:()=>Is,axAIGoogleGeminiDefaultCreativeConfig:()=>ca,axAIGrokBestConfig:()=>Ia,axAIGrokDefaultConfig:()=>to,axAIHuggingFaceCreativeConfig:()=>ua,axAIHuggingFaceDefaultConfig:()=>Cs,axAIMistralBestConfig:()=>pa,axAIMistralDefaultConfig:()=>Hr,axAIOllamaDefaultConfig:()=>ws,axAIOllamaDefaultCreativeConfig:()=>da,axAIOpenAIBestConfig:()=>Or,axAIOpenAICreativeConfig:()=>kr,axAIOpenAIDefaultConfig:()=>kt,axAIOpenAIFastConfig:()=>Mr,axAIOpenAIResponsesBestConfig:()=>ma,axAIOpenAIResponsesCreativeConfig:()=>ga,axAIOpenAIResponsesDefaultConfig:()=>Kn,axAIOpenRouterDefaultConfig:()=>vs,axAIRekaBestConfig:()=>xa,axAIRekaCreativeConfig:()=>Aa,axAIRekaDefaultConfig:()=>Vn,axAIRekaFastConfig:()=>ya,axAITogetherDefaultConfig:()=>ks,axAIWebLLMCreativeConfig:()=>ba,axAIWebLLMDefaultConfig:()=>Es,axAnalyzeChatPromptRequirements:()=>ha,axAnalyzeRequestRequirements:()=>Mt,axBaseAIDefaultConfig:()=>oe,axBaseAIDefaultCreativeConfig:()=>Ce,axCheckMetricsHealth:()=>Ca,axCreateDefaultColorLogger:()=>ts,axCreateDefaultOptimizerColorLogger:()=>ri,axCreateDefaultOptimizerTextLogger:()=>Cl,axCreateDefaultTextLogger:()=>yi,axCreateFlowColorLogger:()=>mr,axCreateFlowTextLogger:()=>El,axDefaultFlowLogger:()=>Pl,axDefaultMetricsConfig:()=>$s,axDefaultOptimizerLogger:()=>ar,axDefaultOptimizerMetricsConfig:()=>oi,axGetCompatibilityReport:()=>ta,axGetFormatCompatibility:()=>ra,axGetMetricsConfig:()=>wa,axGetOptimizerMetricsConfig:()=>wl,axGetProvidersWithMediaSupport:()=>na,axGlobals:()=>W,axModelInfoAnthropic:()=>Ln,axModelInfoCohere:()=>_r,axModelInfoDeepSeek:()=>Nr,axModelInfoGoogleGemini:()=>Gr,axModelInfoGrok:()=>eo,axModelInfoGroq:()=>Br,axModelInfoHuggingFace:()=>jr,axModelInfoMistral:()=>zr,axModelInfoOpenAI:()=>qt,axModelInfoOpenAIResponses:()=>vr,axModelInfoReka:()=>Qr,axModelInfoTogether:()=>Xr,axModelInfoWebLLM:()=>Zr,axProcessContentForProvider:()=>Jr,axRAG:()=>Hl,axScoreProvidersForRequest:()=>Pr,axSelectOptimalProvider:()=>Fr,axSpanAttributes:()=>K,axSpanEvents:()=>rt,axUpdateMetricsConfig:()=>Ra,axUpdateOptimizerMetricsConfig:()=>Rl,axValidateChatRequestMessage:()=>Dt,axValidateChatResponseResult:()=>Sr,axValidateProviderCapabilities:()=>hs,f:()=>le,flow:()=>qo,s:()=>Sl});module.exports=rc($u);function He({model:i,modelInfo:e,models:t}){let n=t?.find(c=>c.key===i),r=n&&"model"in n?n.model:i,o=e.find(c=>c.name===i);if(o)return o;let s=e.find(c=>c.name===r);if(s)return s;let a=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),l=e.find(c=>c.name===a);return l||null}var Xo=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function ve(){return Xo.randomUUID()}async function oc(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Xo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var Yo=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return oc(this.data)}};function _e(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new Yo}function di(){return Xo}var br=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`);this.buffer=n.pop()||"";for(let r of n)r===""?this.processEvent(e):this.parseLine(r)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
4
4
|
`)?`
|
|
5
5
|
`:"")+e.trim();return}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=r;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
6
6
|
`)?`
|
|
7
7
|
`:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var Zo=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)}},Ir=class extends TransformStream{constructor(){super(new Zo)}};var sc={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},ic=globalThis.TextDecoderStream??Ir,Oe=class extends Error{constructor(t,n,r,o,s={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=ve(),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()}},qe=class extends Oe{constructor(t,n,r,o,s,a,l){let c=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${c}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Ne=class extends Oe{constructor(t,n,r,o,s){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},ht=class extends Oe{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name="AxAIServiceResponseError"}},Ke=class extends Oe{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},tt=class extends Oe{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name="AxAIServiceTimeoutError"}},Fn=class extends qe{constructor(e,t,n,r,o,s){super(e,t,n,r,o,s),this.name="AxTokenLimitError"}},
|
|
8
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},qe=class extends Oe{constructor(t,n,r,o,s,a,l){let c=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${c}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Ne=class extends Oe{constructor(t,n,r,o,s){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},ht=class extends Oe{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name="AxAIServiceResponseError"}},Ke=class extends Oe{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},tt=class extends Oe{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name="AxAIServiceTimeoutError"}},Fn=class extends qe{constructor(e,t,n,r,o,s){super(e,t,n,r,o,s),this.name="AxTokenLimitError"}},Lt=class extends Oe{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name="AxAIServiceAbortedError"}},ft=class extends Oe{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name="AxAIServiceAuthenticationError"}},de=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=ve()}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
9
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},We=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=ve()}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
10
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},nt=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=ve()}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 es(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 mi(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function ac(i){if(!i)return;let e=Number(i);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(i);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function lc(){return{startTime:Date.now(),retryCount:0}}function gi(i){i.retryCount++,i.lastRetryTime=Date.now()}function hi(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Ne&&!(i instanceof ft)}var ke=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={...sc,...i.retry},n=i.timeout,r=lc(),o=i.verbose??!1,s,a=new URL(i.url),l=`${[a.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${a.search}`,c=new URL(l,a);if(i.corsProxy){let d=c.href;c=new URL(`${i.corsProxy}?url=${encodeURIComponent(d)}`)}let u=ve();if(i.validateRequest&&!await i.validateRequest(e))throw new ht("Invalid request data",c.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":c.href,"request.id":u,"request.startTime":r.startTime});let p=0;for(;;){let d=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new
|
|
11
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function es(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 mi(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function ac(i){if(!i)return;let e=Number(i);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(i);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function lc(){return{startTime:Date.now(),retryCount:0}}function gi(i){i.retryCount++,i.lastRetryTime=Date.now()}function hi(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Ne&&!(i instanceof ft)}var ke=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={...sc,...i.retry},n=i.timeout,r=lc(),o=i.verbose??!1,s,a=new URL(i.url),l=`${[a.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${a.search}`,c=new URL(l,a);if(i.corsProxy){let d=c.href;c=new URL(`${i.corsProxy}?url=${encodeURIComponent(d)}`)}let u=ve();if(i.validateRequest&&!await i.validateRequest(e))throw new ht("Invalid request data",c.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":c.href,"request.id":u,"request.startTime":r.startTime});let p=0;for(;;){let d=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Lt(c.href,i.abortSignal.reason,e,{metrics:r});let m=()=>{d.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",m,{once:!0});let g=d.abort.bind(d);d.abort=h=>{i.abortSignal.removeEventListener("abort",m),g(h)}}n&&(s=setTimeout(()=>{d.abort("Request timeout")},n));try{o&&console.log(`
|
|
12
12
|
--- [AxAI API Request] ---
|
|
13
13
|
`,`URL: ${c.href}
|
|
14
14
|
`,`Method: ${i.put?"PUT":"POST"}
|
|
@@ -28,7 +28,7 @@ Body:`,JSON.stringify(e,null,2),`
|
|
|
28
28
|
`),!m.body)throw new ht("Response body is null",c.href,e,{metrics:r});let g,h=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(y){let b=m.body.getReader(),I=new TextDecoder,T="";async function v(){try{for(;;){let{done:k,value:R}=await b.read();if(k){x=!0,y.close();break}T+=I.decode(R,{stream:!0});let C=T.split(`
|
|
29
29
|
|
|
30
30
|
`);T=C.pop()||"";for(let O of C){if(!O.trim())continue;let w=O.split(`
|
|
31
|
-
`),E="",S="message";for(let F of w)F.startsWith("data: ")?E=F.slice(6):F.startsWith("event: ")&&(S=F.slice(7));if(E){if(E==="[DONE]"){y.close();return}try{let F=JSON.parse(E);g=F,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),y.enqueue(F),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":S})}catch(F){o&&console.warn("Skipping non-JSON SSE data:",E,F)}}}}}catch(k){let R=k,C={...r,streamDuration:Date.now()-r.startTime};R.name==="AbortError"||R.message?.includes("aborted")?y.error(new Ke(c.href,e,g,{streamMetrics:C})):y.error(new Ne(R,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:C}))}finally{b.releaseLock()}}v()}});let A=new TransformStream({transform(y,b){g=y,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),b.enqueue(y),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),x=!1;return new ReadableStream({start(y){let b=m.body.pipeThrough(new ic).pipeThrough(new br).pipeThrough(A).getReader();async function I(){try{for(;;){let{done:T,value:v}=await b.read();if(T){x||(x=!0,y.close());break}if(x)break;y.enqueue(v)}}catch(T){let v=T,k={...r,streamDuration:Date.now()-r.startTime};throw v.name==="AbortError"||v.message?.includes("aborted")?y.error(new Ke(c.href,e,g,{streamMetrics:k})):v instanceof TypeError&&v.message.includes("cancelled")?y.error(new Ke(c.href,e,g,{streamMetrics:k,cancelReason:"Stream cancelled by client"})):y.error(new Ne(v,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:k})),v}finally{s&&clearTimeout(s),b.releaseLock()}}I()},cancel(){x=!0}})}catch(m){if(m instanceof Error&&m.name==="AbortError")throw i.abortSignal?.aborted?new
|
|
31
|
+
`),E="",S="message";for(let F of w)F.startsWith("data: ")?E=F.slice(6):F.startsWith("event: ")&&(S=F.slice(7));if(E){if(E==="[DONE]"){y.close();return}try{let F=JSON.parse(E);g=F,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),y.enqueue(F),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":S})}catch(F){o&&console.warn("Skipping non-JSON SSE data:",E,F)}}}}}catch(k){let R=k,C={...r,streamDuration:Date.now()-r.startTime};R.name==="AbortError"||R.message?.includes("aborted")?y.error(new Ke(c.href,e,g,{streamMetrics:C})):y.error(new Ne(R,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:C}))}finally{b.releaseLock()}}v()}});let A=new TransformStream({transform(y,b){g=y,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),b.enqueue(y),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),x=!1;return new ReadableStream({start(y){let b=m.body.pipeThrough(new ic).pipeThrough(new br).pipeThrough(A).getReader();async function I(){try{for(;;){let{done:T,value:v}=await b.read();if(T){x||(x=!0,y.close());break}if(x)break;y.enqueue(v)}}catch(T){let v=T,k={...r,streamDuration:Date.now()-r.startTime};throw v.name==="AbortError"||v.message?.includes("aborted")?y.error(new Ke(c.href,e,g,{streamMetrics:k})):v instanceof TypeError&&v.message.includes("cancelled")?y.error(new Ke(c.href,e,g,{streamMetrics:k,cancelReason:"Stream cancelled by client"})):y.error(new Ne(v,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:k})),v}finally{s&&clearTimeout(s),b.releaseLock()}}I()},cancel(){x=!0}})}catch(m){if(m instanceof Error&&m.name==="AbortError")throw i.abortSignal?.aborted?new Lt(c.href,i.abortSignal.reason,e,{metrics:r}):new tt(c.href,n||0,e,{metrics:r});let g=m;if(!(m instanceof Oe)&&m instanceof Error&&(g=new Ne(m,c.href,e,void 0,{metrics:r})),i.span?.isRecording()&&(i.span.recordException(g),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),g instanceof Ne&&hi(g,void 0,p,t)){let h=mi(p,t);p++,gi(r),i.span?.addEvent("retry",{attempt:p,delay:h,error:g.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(f=>setTimeout(f,h));continue}throw g instanceof Oe&&(g.context.metrics=r),g}finally{s!==void 0&&clearTimeout(s)}}};var Gt=require("@opentelemetry/api");var W={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var $e=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 Qu=new $e,fi=i=>{console.log(i)},xi=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
|
|
32
32
|
${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
|
|
33
33
|
${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
|
|
34
34
|
`;if(typeof i.content=="string")return r+n(i.content,"green");let o=i.content.map(s=>{if(s.type==="text")return n(s.text,"green");if(s.type==="image"){let a=e?"[Image]":`[Image: ${s.image}]`;return n(a,"green")}if(s.type==="audio"){let a=e?"[Audio]":`[Audio: ${s.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
|
|
@@ -164,9 +164,9 @@ ${e}
|
|
|
164
164
|
`,n.value.forEach(o=>{r+=`- ${o.title||o.url}
|
|
165
165
|
`,o.description&&(r+=` ${o.description}
|
|
166
166
|
`)}),r+=`${e}
|
|
167
|
-
`;break}default:r=JSON.stringify(n,null,2)}i(r)}};var K={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"},rt={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"},ns=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(ns||{}),rs=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(rs||{});var os=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()}},Tr=class extends TransformStream{constructor(e,t){super(new os(e,t))}};function Cr(i,e){for(let t of e){let n=i.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var bi=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Ii=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function Ti(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?Cr(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Ci=(i,e)=>{e({name:"FunctionResults",value:i})},ss=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},Ri=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},wi=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},Si=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var vi=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Oi=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},ki=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var wr=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},Ot=(...i)=>{let e={};for(let t of i)t&&Object.assign(e,t);return e},Rr,Mi=i=>{if(Rr)return Rr;if(i)return Rr=cc(i),Rr};var cc=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"}),cacheReadTokensCounter:i.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:i.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),Ei=(i,e,t,n,r,o)=>{try{if(i.latencyHistogram){let s=wr({operation:e,ai_service:n,...r?{model:r}:{},...o});i.latencyHistogram.record(t,s)}}catch(s){console.warn("Failed to record latency metric:",s)}},Pi=(i,e,t,n,r,o,s,a)=>{let l={operation:e,ai_service:o,...s?{model:s}:{},...a};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,l),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,l),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,l)},Fi=(i,e,t,n,r)=>{try{if(i.errorCounter){let o=wr({operation:e,ai_service:t,...n?{model:n}:{},...r});i.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},_i=(i,e,t,n,r,o)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ni=(i,e,t,n,r)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},_n=(i,e,t,n,r,o)=>{try{let s=wr({ai_service:n,...r?{model:r}:{},...o});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...s}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,s),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,s)}catch(s){console.warn("Failed to record token metric:",s)}},$i=(i,e,t,n,r,o)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Di=(i,e,t,n,r,o)=>{let s={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...o};i.functionCallsCounter&&i.functionCallsCounter.add(1,s),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,s)},is=(i,e,t,n,r,o)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},as=(i,e,t,n,r,o)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Li=(i,e,t,n,r,o)=>{let s={...n?{ai_service:n}:{},...r?{model:r}:{},...o};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,s),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,s)},ls=(i,e,t,n,r,o)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Gi=(i,e,t,n,r)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ui=(i,e,t,n,r)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Bi=(i,e,t,n,r)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},ji=(i,e,t,n,r)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},qi=(i,e,t,n,r)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},zi=(i,e,t,n,r,o)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...o})},cs=(i,e,t,n,r,o)=>{try{if(t<=0)return;let s=wr({ai_service:n,...r?{model:r}:{},...o});e==="read"&&i.cacheReadTokensCounter&&i.cacheReadTokensCounter.add(t,s),e==="write"&&i.cacheWriteTokensCounter&&i.cacheWriteTokensCounter.add(t,s)}catch(s){console.warn("Failed to record cache token metric:",s)}};function Hi(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function ot(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Hi(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Hi(e.item)}`),new Error(t.join(`
|
|
168
|
-
`))}function Lt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let u=o.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=o.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(u)}`)}let c="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(s)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,s=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!s&&!a&&!l&&ot("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:i}),n!==void 0&&typeof n!="string"&&ot("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&ot("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&&ot("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&&ot("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&&ot("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)ot("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&ot("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&ot("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&&ot("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&ot("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 Sr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&(!r.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let s=r.thoughtBlocks[o];if(typeof s!="object"||s===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(s)}`);if(typeof s.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(s.data)}`);if(typeof s.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(s.encrypted)}`);if(s.signature!==void 0&&typeof s.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(s.signature)}`)}}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var us=new Map;function uc(i){return`${i.providerName}:${i.contentHash}`}function pc(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function dc(i){let e=_e("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)pc(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var oe=()=>structuredClone({temperature:0}),Ce=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Ae=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??W.tracer,this.meter=a.meter??W.meter,this.modelInfo=o,this.models=c,this.id=ve();let u=this.getModel(s.model)??s.model,p=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:p},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&mc(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=W.logger??Ai;corsProxy;retry;customLabels;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Mi(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??W.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??W.tracer,this.meter=e.meter??W.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??W.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(){return Ot(W.customLabels,this.customLabels)}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,s)=>o+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,s=this.getMergedCustomLabels();Ei(r,e,t,this.name,o,s),Pi(r,e,n.mean,n.p95,n.p99,this.name,o,s)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,s=this.getMergedCustomLabels();Ni(r,e,this.name,o,s),t&&Fi(r,e,this.name,o,s),_i(r,e,n.rate,this.name,o,s)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:s,cacheReadTokens:a,cacheCreationTokens:l}=e.tokens,c=this.getMergedCustomLabels();n&&_n(t,"input",n,this.name,e.model,c),r&&_n(t,"output",r,this.name,e.model,c),o&&_n(t,"total",o,this.name,e.model,c),s&&_n(t,"thoughts",s,this.name,e.model,c),a&&cs(t,"read",a,this.name,e.model,c),l&&cs(t,"write",l,this.name,e.model,c)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&Di(n,r.function.name,void 0,this.name,t,this.getMergedCustomLabels())}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Bi(t,e,this.name,n,this.getMergedCustomLabels())}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ji(t,e,this.name,n,this.getMergedCustomLabels())}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=this.getMergedCustomLabels(),l=s?.stream??!1;$i(r,"chat",l,this.name,o,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);zi(r,c,u,this.name,o,a);let p=this.calculatePromptLength(e);Gi(r,p,this.name,o,a),Li(r,s?.temperature,s?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&qi(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(is(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(as(r,"chat",g,this.name,o,a),m.results)for(let A of m.results)A.functionCalls&&this.recordFunctionCallMetrics(A.functionCalls,this.lastUsedChatModel);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);h>0&&Ui(r,h,this.name,o,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&ls(r,"chat",f,this.name,o,a)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.getMergedCustomLabels(),s=this.calculateRequestSize(e);is(n,"embed",s,this.name,r,o);let a=this.calculateResponseSize(t);as(n,"embed",a,this.name,r,o);let l=this.estimateCostByName(r,t.modelUsage);l>0&&ls(n,"embed",l,this.name,r,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return o=await this._chat1(e,l),o}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat")),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)Lt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(c=>c.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Gt.SpanKind.SERVER,attributes:{[K.LLM_SYSTEM]:this.name,[K.LLM_OPERATION_NAME]:"chat",[K.LLM_REQUEST_MODEL]:n,[K.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[K.LLM_REQUEST_TEMPERATURE]:o.temperature,[K.LLM_REQUEST_TOP_P]:o.topP??"Not set",[K.LLM_REQUEST_TOP_K]:o.topK??"Not set",[K.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[K.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[K.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[K.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Gt.context.active(),async c=>await this._chat2(n,o,e,t,c)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(y=>this.cleanupFunctionSchema(y)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&bi(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(y=>{if(y.role==="assistant"){let{content:b,name:I,cache:T}=y;return{role:"assistant",content:b,name:I,cache:T}}return y.role==="function"?{role:"user",content:y.result}:y}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,o),h=async()=>{if(g?.preparedRequest){let{apiConfig:T,request:v}=g.preparedRequest;return o?.isRecording()&&Ki(n,o,this.excludeContentFromTrace),await ke({name:T.name,url:this.apiURL,localCall:T.localCall,headers:await this.buildHeaders(T.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},v)}let[y,b]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Ki(n,o,this.excludeContentFromTrace),await ke({name:y.name,url:this.apiURL,localCall:y.localCall,headers:await this.buildHeaders(y.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},b)},f=r?.rateLimiter??this.rt,A=f?await f(h,{modelUsage:this.modelUsage}):await h();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let y=this.aiImpl.createChatStreamResp.bind(this),b=k=>R=>{let C=y(R,k);if(C.sessionId=r?.sessionId,!C.modelUsage){let O=this.aiImpl.getTokenUsage();O&&(C.modelUsage={ai:this.name,model:e,tokens:O})}return this.modelUsage=C.modelUsage,this.recordTokenUsage(C.modelUsage),o?.isRecording()&&Wi(C,o,this.excludeContentFromTrace),C},I=async k=>{o?.isRecording()&&o.end(),s&&Ti(k,r?.logger??this.logger)};if(typeof window<"u"){let k=A,R={},C=[],O=r?.abortSignal??this.abortSignal;return new ReadableStream({start:w=>{let E=k.getReader(),S=()=>{try{E.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{w.error(new DOMException("Aborted","AbortError"))}catch{w.error(new Error("Aborted"))}};if(O){if(O.aborted){S();return}O.addEventListener("abort",S,{once:!0})}async function F(){try{for(;;){let{done:$,value:M}=await E.read();if($){I&&await I(C),w.close();break}let P=b(R)(M);P&&(C.push(P),w.enqueue(P))}}catch($){if(w.error($),o?.isRecording())try{o.end()}catch{}}finally{if(E.releaseLock(),O)try{O.removeEventListener("abort",S)}catch{}}}F()}})}return A.pipeThrough(new Tr(b({}),I))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(A);if(x.sessionId=r?.sessionId,!x.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(x.modelUsage={ai:this.name,model:e,tokens:y})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage)),o?.isRecording()&&(Wi(x,o,this.excludeContentFromTrace),o.end()),s&&Ii(x,r?.logger??this.logger),x}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Gt.SpanKind.SERVER,attributes:{[K.LLM_SYSTEM]:this.name,[K.LLM_OPERATION_NAME]:"embeddings",[K.LLM_REQUEST_MODEL]:n}},t?.traceContext??Gt.context.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&vi(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await o(l);return await ke({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(rt.GEN_AI_USAGE,{[K.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[K.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[K.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Oi(d.embeddings,n?.logger??this.logger),r?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}async handleContextCaching(e,t,n,r){let o=n?.contextCache;if(!o)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let l=o.ttlSeconds??3600,c=o.refreshWindowSeconds??300,u=o.minTokens??2048;if(o.name)return this.useCacheByName(e,t,o.name,n,r);let p=dc(t.chatPrompt);if(!p||p===_e("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=uc(d),g=Date.now(),h=o.registry,f=h?await h.get(m):us.get(m);if(f&&f.expiresAt>g){if(f.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let b={cacheName:f.cacheName,expiresAt:g+l*1e3,tokenCount:f.tokenCount};h?await h.set(m,b):us.set(m,{...b,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let y=await this.executeCacheOperation(x,n,r);if(y){let b={cacheName:y.name,expiresAt:new Date(y.expiresAt).getTime(),tokenCount:y.tokenCount};return h?await h.set(m,b):us.set(m,{...b,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,y.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let s=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:s.apiConfig,request:s.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let o=await ke({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(o)}catch(o){n?.addEvent("context_cache.error",{type:e.type,error:o instanceof Error?o.message:String(o)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Ki(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(rt.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(rt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(rt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(rt.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
|
|
169
|
-
`)),e.addEvent(rt.GEN_AI_USER_MESSAGE,r)}function Wi(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[K.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(rt.GEN_AI_USAGE,{[K.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[K.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[K.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(rt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Vi(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 mc(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 Nn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(Nn||{}),$n=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))($n||{});var Dn=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var Tt=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Tt(r)]))),e.items&&(e.items=Tt(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Tt(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Tt(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Tt(n))),e},ds=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...oe()}),Qi=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...oe()}),ps=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.some(C=>"cache"in C&&C.cache)||e.functions?.some(C=>C.cache),l=e.chatPrompt.filter(C=>C.role==="system"),c=l.map((C,O)=>({type:"text",text:C.content,...C.cache||a&&O===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(C=>C.role!=="system"),p=e.functions?.map((C,O,w)=>{let E={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},S=C.parameters?Tt(C.parameters):void 0;return S===void 0||S&&typeof S=="object"&&Object.keys(S).length===0?S={...E}:S&&typeof S=="object"&&S.type==="object"&&(!("properties"in S)||!S.properties||Object.keys(S.properties).length===0)&&(S={...S,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:C.name,description:C.description,input_schema:S,...C.cache||a&&O===w.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(C=>C&&typeof C=="object"&&"type"in C?C:{name:C.name,description:C.description,input_schema:C.input_schema?Tt(C.input_schema):void 0,...C.cache_control?{cache_control:C.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let h=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,x=e.modelConfig?.topP,y=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 I;if(this.config.thinking?.budget_tokens&&(I=this.config.thinking),t?.thinkingTokenBudget){let C=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":I=void 0;break;case"minimal":I={type:"enabled",budget_tokens:C?.minimal??1024};break;case"low":I={type:"enabled",budget_tokens:C?.low??5e3};break;case"medium":I={type:"enabled",budget_tokens:C?.medium??1e4};break;case"high":I={type:"enabled",budget_tokens:C?.high??2e4};break;case"highest":I={type:"enabled",budget_tokens:C?.highest??32e3};break}}if(!I&&t?.thinkingTokenBudget===void 0){let C=this.config.thinkingTokenBudgetLevels}let T=gc(u,!!I);T.some(C=>C.role==="assistant"&&Array.isArray(C.content)&&C.content.length>0&&C.content[0]?.type==="tool_use")&&(I=void 0);let k;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let C=e.responseFormat.schema.schema||e.responseFormat.schema;k={type:"json_schema",schema:Tt(C)},this.usedStructuredOutput=!0}let R={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...h?{max_tokens:h}:{},...f&&f.length>0?{stop_sequences:f}:{},...A!==void 0&&!I?{temperature:A}:{},...x!==void 0&&(!I||x>=.95)?{top_p:x}:{},...y&&!I?{top_k:y}:{},...s,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...I?{thinking:I}:{},...k?{output_format:k}:{},messages:T};return[o,R]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=Ji(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;s.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;s.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),s.length>0&&(l.thoughtBlocks=s,l.thought=s.map(u=>u.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let c=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:c,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new de(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Ji(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},Ut=class i extends Ae{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){let a=t!==void 0&&n!==void 0,l,c;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={...ds(),...r},p=new ps(u,a),d=g=>{let h=He({model:g,modelInfo:Dn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,f=h?.config;if(!f)return g;let A={};f.maxTokens!==void 0&&(A.maxTokens=f.maxTokens),f.temperature!==void 0&&(A.temperature=f.temperature),f.topP!==void 0&&(A.topP=f.topP),f.topK!==void 0&&(A.topK=f.topK),f.presencePenalty!==void 0&&(A.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(A.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(A.stopSequences=f.stopSequences),f.endSequences!==void 0&&(A.endSequences=f.endSequences),f.stream!==void 0&&(A.stream=f.stream),f.n!==void 0&&(A.n=f.n);let x={...h};Object.keys(A).length>0&&(x.modelConfig={...h.modelConfig??{},...A});let y=f.thinking?.thinkingTokenBudget;if(typeof y=="number"){let b=u.thinkingTokenBudgetLevels,I=[["minimal",b?.minimal??200],["low",b?.low??800],["medium",b?.medium??5e3],["high",b?.high??1e4],["highest",b?.highest??24500]],T="minimal",v=Number.POSITIVE_INFINITY;for(let[k,R]of I){let C=Math.abs(y-R);C<v&&(v=C,T=k)}x.thinkingTokenBudget=T}return f.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!f.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Dn,defaults:{model:u.model},options:o,supportFor:d,models:m??s})}};function gc(i,e){let t=i.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?s.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):s.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,c=o[l];c&&c.type==="text"&&(o[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=hc(t);return fc(n)}function hc(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function fc(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Ji(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 Ln=(w=>(w.GPT4="gpt-4",w.GPT41="gpt-4.1",w.GPT41Mini="gpt-4.1-mini",w.GPT41Nano="gpt-4.1-nano",w.GPT4O="gpt-4o",w.GPT4OMini="gpt-4o-mini",w.GPT4ChatGPT4O="chatgpt-4o-latest",w.GPT4Turbo="gpt-4-turbo",w.GPT35Turbo="gpt-3.5-turbo",w.GPT35TurboInstruct="gpt-3.5-turbo-instruct",w.GPT35TextDavinci002="text-davinci-002",w.GPT3TextBabbage002="text-babbage-002",w.GPT3TextAda001="text-ada-001",w.GPT5="gpt-5",w.GPT5Nano="gpt-5-nano",w.GPT5Mini="gpt-5-mini",w.GPT5Chat="gpt-5-chat",w.GPT5Pro="gpt-5-pro",w.GPT51="gpt-5.1",w.GPT51ChatLatest="gpt-5.1-chat-latest",w.GPT52="gpt-5.2",w.GPT52ChatLatest="gpt-5.2-chat-latest",w.GPT52Pro="gpt-5.2-pro",w.O1="o1",w.O1Mini="o1-mini",w.O3="o3",w.O3Mini="o3-mini",w.O4Mini="o4-mini",w))(Ln||{}),Bt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Bt||{});var jt=(S=>(S.GPT4="gpt-4",S.GPT41="gpt-4.1",S.GPT41Mini="gpt-4.1-mini",S.GPT41Nano="gpt-4.1-nano",S.GPT4O="gpt-4o",S.GPT4OMini="gpt-4o-mini",S.GPT4ChatGPT4O="chatgpt-4o-latest",S.GPT4Turbo="gpt-4-turbo",S.GPT35Turbo="gpt-3.5-turbo",S.GPT35TurboInstruct="gpt-3.5-turbo-instruct",S.GPT35TextDavinci002="text-davinci-002",S.GPT3TextBabbage002="text-babbage-002",S.GPT3TextAda001="text-ada-001",S.GPT5="gpt-5",S.GPT5Nano="gpt-5-nano",S.GPT5Mini="gpt-5-mini",S.GPT5Chat="gpt-5-chat",S.GPT5Pro="gpt-5-pro",S.GPT51="gpt-5.1",S.GPT51ChatLatest="gpt-5.1-chat-latest",S.GPT52="gpt-5.2",S.GPT52ChatLatest="gpt-5.2-chat-latest",S.GPT52Pro="gpt-5.2-pro",S.O1Pro="o1-pro",S.O1="o1",S.O1Mini="o1-mini",S.O3Pro="o3-pro",S.O3="o3",S.O3Mini="o3-mini",S.O4Mini="o4-mini",S))(jt||{});var qt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],vr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var xc=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},kt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...oe()}),Or=()=>structuredClone({...kt(),model:"gpt-5"}),kr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ce()}),Mr=()=>({...kt(),model:"gpt-5-nano"}),ms=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Ac(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=xc(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...p?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new de(a.message.refusal,e.model,e.id);let l=Yi(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:p,name:d}})=>({id:u,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(p)throw new de(p,void 0,n);let f=Yi(h),A=d?.map(({id:x,index:y,function:{name:b,arguments:I}})=>{typeof x=="string"&&typeof y=="number"&&!s.indexIdMap[y]&&(s.indexIdMap[y]=x);let T=s.indexIdMap[y];return T?{id:T,type:"function",function:{name:b,params:I}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:A,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Yi=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ac(i){return i.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var fe=class extends Ae{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new ms(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},zt=class extends fe{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...qt,...s??[]];let a=c=>{let u=He({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,p=u?.config;if(!p)return c;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let g={...u};Object.keys(d).length>0&&(g.modelConfig={...u.modelConfig??{},...d});let h=p?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",x=Number.POSITIVE_INFINITY;for(let[y,b]of f){let I=Math.abs(h-b);I<x&&(x=I,A=y)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...kt(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var yc=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},bc=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},gs=kt,Xi=kr,Zi=Mr,ea=Or,Ht=class extends fe{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let c={...gs(),...o},u=yc(r),p=bc(u);l=[...qt,...l??[]];let d=g=>{let h=He({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:p&&(h?.supported?.structuredOutputs??!1),functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Er=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.");Ic(e),this.services=[...e].sort(t?.comparator??i.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new i(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}},t=0,n=0,r=0,o=0;for(let s of this.services){let a=s.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,o+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let s of this.services){let a=s.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,s=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=s}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,s=r?.requiresAudio,a=this.services,l=e.model;if((n||o||s)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||s&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),s&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Oe))throw p;switch(p.constructor){case ft:throw p;case qe:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Ne:break;case ht:break;case Ke:break;case tt:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Oe)||r instanceof qe&&![408,429,500,502,503,504].includes(r.status)||r instanceof ft)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let s=this.getNextService(this.services,n);if(!s.service)throw r;this.currentService=s.service,n=s.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Ic(i){let e=i.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function Mt(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let p of u.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function hs(i,e){let t=i.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Pr(i,e){return i.map(t=>{let n=t.getFeatures(),r=hs(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function Fr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Mt(i),r=Pr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function ta(i,e){let t=Mt(i),n=Pr(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function na(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function ra(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var Gn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Gn||{}),Un=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(Un||{});var _r=[{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 xs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...oe()}),sa=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ce()}),fs=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let s=Tc(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,g]of Object.entries(p.parameters.properties))d[m]={description:g.description,type:g.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:s,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[c,u]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Kt=class extends Ae{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...xs(),...t},s=new fs(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let p={};u.maxTokens!==void 0&&(p.maxTokens=u.maxTokens),u.temperature!==void 0&&(p.temperature=u.temperature),u.topP!==void 0&&(p.topP=u.topP),u.topK!==void 0&&(p.topK=u.topK),u.presencePenalty!==void 0&&(p.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(p.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(p.stopSequences=u.stopSequences),u.endSequences!==void 0&&(p.endSequences=u.endSequences),u.stream!==void 0&&(p.stream=u.stream),u.n!==void 0&&(p.n=u.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:_r,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Tc(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=oa(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=oa(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function oa(i){return i?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var Bn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Bn||{});var Nr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var As=()=>structuredClone({model:"deepseek-chat",...oe()}),ia=()=>structuredClone({model:"deepseek-coder",...Ce()}),Wt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...As(),...t};o=[...Nr,...o??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var jn=(x=>(x.Gemini3Flash="gemini-3-flash-preview",x.Gemini3Pro="gemini-3-pro-preview",x.Gemini3ProImage="gemini-3-pro-image-preview",x.Gemini25Pro="gemini-2.5-pro",x.Gemini25Flash="gemini-2.5-flash",x.Gemini25FlashLite="gemini-2.5-flash-lite",x.Gemini20Flash="gemini-2.0-flash",x.Gemini20FlashLite="gemini-2.0-flash-lite",x.Gemini20ProExp="gemini-2.0-pro-exp-02-05",x.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",x.Gemini1Pro="gemini-1.0-pro",x.Gemini15Flash="gemini-1.5-flash",x.Gemini15Flash002="gemini-1.5-flash-002",x.Gemini15Flash8B="gemini-1.5-flash-8b",x.Gemini15Pro="gemini-1.5-pro",x.GeminiFlashLatest="gemini-flash-latest",x.GeminiFlashLiteLatest="gemini-flash-lite-latest",x.GeminiProLatest="gemini-pro-latest",x))(jn||{}),$r=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))($r||{}),Dr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(Dr||{}),Lr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Lr||{}),ys=(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))(ys||{}),aa=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var Gr=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Ur=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,Ur(n)]))),e.items&&(e.items=Ur(e.items)),e},la=[{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"}],Is=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:la,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...oe()}),ca=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:la,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ce()}),bs=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let A=r?"&":"?",x=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${A}key=${x}`}let s=e.chatPrompt.filter(A=>A.role==="system").map(A=>A.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(A=>A.role!=="system");for(let A=0;A<c.length;A++){let x=c[A];switch(x.role){case"user":{let y=Array.isArray(x.content)?x.content.map((b,I)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${I})`)}}):[{text:x.content}];l.push({role:"user",parts:y});break}case"assistant":{let y=[],b=x.thoughtBlocks,I=x.functionCalls&&x.functionCalls.length>0,T=b?.[0],v=b?.map(R=>R.data).join("")??"",k=T?.signature;if(v&&y.push({...I?{}:{thought:!0},text:v,...k&&!I?{thought_signature:k}:{}}),x.functionCalls){let R=x.functionCalls.map((C,O)=>{let w;if(typeof C.function.params=="string"){let S=C.function.params;if(S.trim().length===0)w={};else try{w=JSON.parse(S)}catch{throw new Error(`Failed to parse function params JSON: ${S}`)}}else w=C.function.params;let E={functionCall:{name:C.function.name,args:w}};return k&&O===0&&(E.thought_signature=k),E});y.push(...R)}if(x.content&&y.push({text:x.content}),y.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:y});break}case"function":{let y=[],b=x,I=A;for(;;){if(!("functionId"in b))throw new Error(`Chat prompt functionId is empty (index: ${I})`);if(y.push({functionResponse:{name:b.functionId,response:{result:b.result}}}),I+1<c.length&&c[I+1].role==="function")I++,b=c[I];else break}A=I,l.push({role:"user",parts:y});break}default:throw new Error(`Invalid role: ${JSON.stringify(x)} (index: ${A})`)}}let u=[];if(e.functions&&e.functions.length>0){let A=e.functions.map(x=>{let y={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=x.parameters?Ur(x.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...y}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:x.name,description:x.description,parameters:b}});u.push({function_declarations:A})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let A=this.options.googleMaps,x=A?.enableWidget!==void 0?{enableWidget:A.enableWidget}:{};u.push({google_maps:x})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(A=>A&&Array.isArray(A.function_declarations)&&A.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let A=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...A}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let A=this.config.thinkingTokenBudgetLevels,x=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=A?.minimal??200,x&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=A?.low??800,x&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=A?.medium??5e3,x&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=A?.high??1e4,x&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=A?.highest??24500,x&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let A=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=Ur(A)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new de("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new de("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new de("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new de("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new de("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new de("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new de("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new de("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new de("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){s.thought=c.text;let u=c.thoughtSignature||c.thought_signature;s.thoughtBlocks||(s.thoughtBlocks=[]),s.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else s.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!s.thoughtBlocks||s.thoughtBlocks.length===0)s.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=s.thoughtBlocks[s.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}s.functionCalls=[...s.functionCalls??[],{id:ve(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;s.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(s.citations=[...s.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return s});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}};supportsContextCache=e=>{let t=e;return aa.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:s}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!s||s.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),s&&s.length>0&&(a.contents=s);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let o=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${o}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:o=>{let s=o;if(s?.name)return{name:s.name,expiresAt:s.expireTime,tokenCount:s.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,o=e.modelConfig?.stream??this.config.stream,{dynamicContents:s,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:o?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=o?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain"},u=this.config.safetySettings,p={contents:s,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if("cache"in s&&s.cache){r=o;break}}for(let o=0;o<e.length;o++){let s=e[o];if(s.role==="system"){t={role:"user",parts:[{text:s.content}]};continue}if(r>=0&&o<=r)if(s.role==="user"){let a=[];if(typeof s.content=="string")a.push({text:s.content});else if(Array.isArray(s.content))for(let l of s.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else s.role==="assistant"&&s.content&&n.push({role:"model",parts:[{text:s.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if(!("cache"in s&&s.cache))switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else if(r.role==="assistant"){let o=[];if(r.content&&o.push({text:r.content}),r.functionCalls)for(let s of r.functionCalls){let a;if(typeof s.function.params=="string")try{a=JSON.parse(s.function.params)}catch{a={}}else a=s.function.params??{};o.push({functionCall:{name:s.function.name,args:a}})}o.length>0&&n.push({role:"model",parts:o})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},Vt=class i extends Ae{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,u,p;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Is(),...o},m=new bs(d,c,r,e,s);l=[...Gr,...l??[]];let g=f=>{let A=He({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!1,structuredOutputs:A?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:m.supportsContextCache(f),types:["persistent"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let A=f,x=A?.config;if(!x)return f;let y={};x.maxTokens!==void 0&&(y.maxTokens=x.maxTokens),x.temperature!==void 0&&(y.temperature=x.temperature),x.topP!==void 0&&(y.topP=x.topP),x.topK!==void 0&&(y.topK=x.topK),x.presencePenalty!==void 0&&(y.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(y.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(y.stopSequences=x.stopSequences),x.endSequences!==void 0&&(y.endSequences=x.endSequences),x.stream!==void 0&&(y.stream=x.stream),x.n!==void 0&&(y.n=x.n);let b={...A};Object.keys(y).length>0&&(b.modelConfig={...A.modelConfig??{},...y});let I=x.thinking?.thinkingTokenBudget;if(typeof I=="number"){let T=d.thinkingTokenBudgetLevels,v=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],k="minimal",R=Number.POSITIVE_INFINITY;for(let[C,O]of v){let w=Math.abs(I-O);w<R&&(R=w,k=C)}b.thinkingTokenBudget=k}return x.thinking?.includeThoughts!==void 0&&(b.showThoughts=!!x.thinking.includeThoughts),b});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:h??a})}};var Cc=new $e,Jt=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(Cc.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var qn=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(qn||{});var Br=[{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 Rc=()=>structuredClone({model:"llama-3.3-70b-versatile",...oe()}),Qt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...Rc(),...t},a={...n,streamingUsage:!1};o=[...Br,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new Jt(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var jr=[];var qr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(qr||{});var Cs=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...oe()}),ua=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ce()}),Ts=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:
|
|
167
|
+
`;break}default:r=JSON.stringify(n,null,2)}i(r)}};var K={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"},rt={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"},ns=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(ns||{}),rs=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(rs||{});var os=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()}},Tr=class extends TransformStream{constructor(e,t){super(new os(e,t))}};function Cr(i,e){for(let t of e){let n=i.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var bi=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Ii=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function Ti(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?Cr(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Ci=(i,e)=>{e({name:"FunctionResults",value:i})},ss=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},Ri=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},wi=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},Si=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var vi=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Oi=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},ki=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var wr=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},Ot=(...i)=>{let e={};for(let t of i)t&&Object.assign(e,t);return e},Rr,Mi=i=>{if(Rr)return Rr;if(i)return Rr=cc(i),Rr};var cc=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"}),cacheReadTokensCounter:i.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:i.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),Ei=(i,e,t,n,r,o)=>{try{if(i.latencyHistogram){let s=wr({operation:e,ai_service:n,...r?{model:r}:{},...o});i.latencyHistogram.record(t,s)}}catch(s){console.warn("Failed to record latency metric:",s)}},Pi=(i,e,t,n,r,o,s,a)=>{let l={operation:e,ai_service:o,...s?{model:s}:{},...a};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,l),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,l),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,l)},Fi=(i,e,t,n,r)=>{try{if(i.errorCounter){let o=wr({operation:e,ai_service:t,...n?{model:n}:{},...r});i.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},_i=(i,e,t,n,r,o)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ni=(i,e,t,n,r)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},_n=(i,e,t,n,r,o)=>{try{let s=wr({ai_service:n,...r?{model:r}:{},...o});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...s}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,s),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,s)}catch(s){console.warn("Failed to record token metric:",s)}},$i=(i,e,t,n,r,o)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Li=(i,e,t,n,r,o)=>{let s={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...o};i.functionCallsCounter&&i.functionCallsCounter.add(1,s),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,s)},is=(i,e,t,n,r,o)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},as=(i,e,t,n,r,o)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Di=(i,e,t,n,r,o)=>{let s={...n?{ai_service:n}:{},...r?{model:r}:{},...o};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,s),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,s)},ls=(i,e,t,n,r,o)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Gi=(i,e,t,n,r)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ui=(i,e,t,n,r)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Bi=(i,e,t,n,r)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},ji=(i,e,t,n,r)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},qi=(i,e,t,n,r)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},zi=(i,e,t,n,r,o)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...o})},cs=(i,e,t,n,r,o)=>{try{if(t<=0)return;let s=wr({ai_service:n,...r?{model:r}:{},...o});e==="read"&&i.cacheReadTokensCounter&&i.cacheReadTokensCounter.add(t,s),e==="write"&&i.cacheWriteTokensCounter&&i.cacheWriteTokensCounter.add(t,s)}catch(s){console.warn("Failed to record cache token metric:",s)}};function Hi(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function ot(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Hi(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Hi(e.item)}`),new Error(t.join(`
|
|
168
|
+
`))}function Dt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let u=o.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=o.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(u)}`)}let c="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(s)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,s=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!s&&!a&&!l&&ot("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:i}),n!==void 0&&typeof n!="string"&&ot("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&ot("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&&ot("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&&ot("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&&ot("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)ot("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&ot("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&ot("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&&ot("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&ot("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 Sr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&(!r.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let s=r.thoughtBlocks[o];if(typeof s!="object"||s===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(s)}`);if(typeof s.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(s.data)}`);if(typeof s.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(s.encrypted)}`);if(s.signature!==void 0&&typeof s.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(s.signature)}`)}}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var us=new Map;function uc(i){return`${i.providerName}:${i.contentHash}`}function pc(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function dc(i){let e=_e("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)pc(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var oe=()=>structuredClone({temperature:0}),Ce=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Ae=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??W.tracer,this.meter=a.meter??W.meter,this.modelInfo=o,this.models=c,this.id=ve();let u=this.getModel(s.model)??s.model,p=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:p},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&mc(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=W.logger??Ai;corsProxy;retry;customLabels;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Mi(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??W.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??W.tracer,this.meter=e.meter??W.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??W.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return Ot(W.customLabels,this.customLabels,e)}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((s,a)=>s+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Ei(o,e,t,this.name,s,a),Pi(o,e,r.mean,r.p95,r.p99,this.name,s,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let o=this.getMetricsInstruments();if(o){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Ni(o,e,this.name,s,a),t&&Fi(o,e,this.name,s,a),_i(o,e,r.rate,this.name,s,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:o,totalTokens:s,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:c}=e.tokens,u=this.getMergedCustomLabels(t);r&&_n(n,"input",r,this.name,e.model,u),o&&_n(n,"output",o,this.name,e.model,u),s&&_n(n,"total",s,this.name,e.model,u),a&&_n(n,"thoughts",a,this.name,e.model,u),l&&cs(n,"read",l,this.name,e.model,u),c&&cs(n,"write",c,this.name,e.model,u)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Li(r,o.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Bi(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ji(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=s?.stream??!1;$i(r,"chat",l,this.name,o,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);zi(r,c,u,this.name,o,a);let p=this.calculatePromptLength(e);Gi(r,p,this.name,o,a),Di(r,s?.temperature,s?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&qi(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(is(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(as(r,"chat",g,this.name,o,a),m.results)for(let A of m.results)A.functionCalls&&this.recordFunctionCallMetrics(A.functionCalls,this.lastUsedChatModel,a);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);h>0&&Ui(r,h,this.name,o,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&ls(r,"chat",f,this.name,o,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedEmbedModel,s=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);is(r,"embed",a,this.name,o,s);let l=this.calculateResponseSize(t);as(r,"embed",l,this.name,o,s);let c=this.estimateCostByName(o,t.modelUsage);c>0&&ls(r,"embed",c,this.name,o,s)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return o=await this._chat1(e,l),o}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat",l?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)Dt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(c=>c.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Gt.SpanKind.SERVER,attributes:{[K.LLM_SYSTEM]:this.name,[K.LLM_OPERATION_NAME]:"chat",[K.LLM_REQUEST_MODEL]:n,[K.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[K.LLM_REQUEST_TEMPERATURE]:o.temperature,[K.LLM_REQUEST_TOP_P]:o.topP??"Not set",[K.LLM_REQUEST_TOP_K]:o.topK??"Not set",[K.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[K.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[K.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[K.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Gt.context.active(),async c=>await this._chat2(n,o,e,t,c)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(y=>this.cleanupFunctionSchema(y)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&bi(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(y=>{if(y.role==="assistant"){let{content:b,name:I,cache:T}=y;return{role:"assistant",content:b,name:I,cache:T}}return y.role==="function"?{role:"user",content:y.result}:y}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,o),h=async()=>{if(g?.preparedRequest){let{apiConfig:T,request:v}=g.preparedRequest;return o?.isRecording()&&Ki(n,o,this.excludeContentFromTrace),await ke({name:T.name,url:this.apiURL,localCall:T.localCall,headers:await this.buildHeaders(T.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},v)}let[y,b]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Ki(n,o,this.excludeContentFromTrace),await ke({name:y.name,url:this.apiURL,localCall:y.localCall,headers:await this.buildHeaders(y.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},b)},f=r?.rateLimiter??this.rt,A=f?await f(h,{modelUsage:this.modelUsage}):await h();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let y=this.aiImpl.createChatStreamResp.bind(this),b=k=>R=>{let C=y(R,k);if(C.sessionId=r?.sessionId,!C.modelUsage){let O=this.aiImpl.getTokenUsage();O&&(C.modelUsage={ai:this.name,model:e,tokens:O})}return this.modelUsage=C.modelUsage,this.recordTokenUsage(C.modelUsage,r?.customLabels),o?.isRecording()&&Wi(C,o,this.excludeContentFromTrace),C},I=async k=>{o?.isRecording()&&o.end(),s&&Ti(k,r?.logger??this.logger)};if(typeof window<"u"){let k=A,R={},C=[],O=r?.abortSignal??this.abortSignal;return new ReadableStream({start:w=>{let E=k.getReader(),S=()=>{try{E.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{o?.isRecording()&&o.end()}catch{}try{w.error(new DOMException("Aborted","AbortError"))}catch{w.error(new Error("Aborted"))}};if(O){if(O.aborted){S();return}O.addEventListener("abort",S,{once:!0})}async function F(){try{for(;;){let{done:$,value:M}=await E.read();if($){I&&await I(C),w.close();break}let P=b(R)(M);P&&(C.push(P),w.enqueue(P))}}catch($){if(w.error($),o?.isRecording())try{o.end()}catch{}}finally{if(E.releaseLock(),O)try{O.removeEventListener("abort",S)}catch{}}}F()}})}return A.pipeThrough(new Tr(b({}),I))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(A);if(x.sessionId=r?.sessionId,!x.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(x.modelUsage={ai:this.name,model:e,tokens:y})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage,r?.customLabels)),o?.isRecording()&&(Wi(x,o,this.excludeContentFromTrace),o.end()),s&&Ii(x,r?.logger??this.logger),x}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&o&&this.recordEmbedMetrics(e,o,a)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Gt.SpanKind.SERVER,attributes:{[K.LLM_SYSTEM]:this.name,[K.LLM_OPERATION_NAME]:"embeddings",[K.LLM_REQUEST_MODEL]:n}},t?.traceContext??Gt.context.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&vi(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await o(l);return await ke({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(rt.GEN_AI_USAGE,{[K.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[K.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[K.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Oi(d.embeddings,n?.logger??this.logger),r?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}async handleContextCaching(e,t,n,r){let o=n?.contextCache;if(!o)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let l=o.ttlSeconds??3600,c=o.refreshWindowSeconds??300,u=o.minTokens??2048;if(o.name)return this.useCacheByName(e,t,o.name,n,r);let p=dc(t.chatPrompt);if(!p||p===_e("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=uc(d),g=Date.now(),h=o.registry,f=h?await h.get(m):us.get(m);if(f&&f.expiresAt>g){if(f.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let b={cacheName:f.cacheName,expiresAt:g+l*1e3,tokenCount:f.tokenCount};h?await h.set(m,b):us.set(m,{...b,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let y=await this.executeCacheOperation(x,n,r);if(y){let b={cacheName:y.name,expiresAt:new Date(y.expiresAt).getTime(),tokenCount:y.tokenCount};return h?await h.set(m,b):us.set(m,{...b,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,y.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let s=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:s.apiConfig,request:s.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let o=await ke({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(o)}catch(o){n?.addEvent("context_cache.error",{type:e.type,error:o instanceof Error?o.message:String(o)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Ki(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(rt.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(rt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(rt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(rt.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
|
|
169
|
+
`)),e.addEvent(rt.GEN_AI_USER_MESSAGE,r)}function Wi(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[K.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(rt.GEN_AI_USAGE,{[K.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[K.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[K.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(rt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Vi(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 mc(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 Nn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(Nn||{}),$n=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))($n||{});var Ln=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var Tt=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Tt(r)]))),e.items&&(e.items=Tt(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Tt(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Tt(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Tt(n))),e},ds=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...oe()}),Qi=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...oe()}),ps=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.some(C=>"cache"in C&&C.cache)||e.functions?.some(C=>C.cache),l=e.chatPrompt.filter(C=>C.role==="system"),c=l.map((C,O)=>({type:"text",text:C.content,...C.cache||a&&O===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(C=>C.role!=="system"),p=e.functions?.map((C,O,w)=>{let E={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},S=C.parameters?Tt(C.parameters):void 0;return S===void 0||S&&typeof S=="object"&&Object.keys(S).length===0?S={...E}:S&&typeof S=="object"&&S.type==="object"&&(!("properties"in S)||!S.properties||Object.keys(S.properties).length===0)&&(S={...S,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:C.name,description:C.description,input_schema:S,...C.cache||a&&O===w.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(C=>C&&typeof C=="object"&&"type"in C?C:{name:C.name,description:C.description,input_schema:C.input_schema?Tt(C.input_schema):void 0,...C.cache_control?{cache_control:C.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let h=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,x=e.modelConfig?.topP,y=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 I;if(this.config.thinking?.budget_tokens&&(I=this.config.thinking),t?.thinkingTokenBudget){let C=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":I=void 0;break;case"minimal":I={type:"enabled",budget_tokens:C?.minimal??1024};break;case"low":I={type:"enabled",budget_tokens:C?.low??5e3};break;case"medium":I={type:"enabled",budget_tokens:C?.medium??1e4};break;case"high":I={type:"enabled",budget_tokens:C?.high??2e4};break;case"highest":I={type:"enabled",budget_tokens:C?.highest??32e3};break}}if(!I&&t?.thinkingTokenBudget===void 0){let C=this.config.thinkingTokenBudgetLevels}let T=gc(u,!!I);T.some(C=>C.role==="assistant"&&Array.isArray(C.content)&&C.content.length>0&&C.content[0]?.type==="tool_use")&&(I=void 0);let k;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let C=e.responseFormat.schema.schema||e.responseFormat.schema;k={type:"json_schema",schema:Tt(C)},this.usedStructuredOutput=!0}let R={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...h?{max_tokens:h}:{},...f&&f.length>0?{stop_sequences:f}:{},...A!==void 0&&!I?{temperature:A}:{},...x!==void 0&&(!I||x>=.95)?{top_p:x}:{},...y&&!I?{top_k:y}:{},...s,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...I?{thinking:I}:{},...k?{output_format:k}:{},messages:T};return[o,R]};createChatResp=e=>{if(e.type==="error")throw new de(e.error.message,void 0,void 0);let t=Ji(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;s.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;s.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),s.length>0&&(l.thoughtBlocks=s,l.thought=s.map(u=>u.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let c=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:c,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new de(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Ji(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},Ut=class i extends Ae{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){let a=t!==void 0&&n!==void 0,l,c;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={...ds(),...r},p=new ps(u,a),d=g=>{let h=He({model:g,modelInfo:Ln,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,f=h?.config;if(!f)return g;let A={};f.maxTokens!==void 0&&(A.maxTokens=f.maxTokens),f.temperature!==void 0&&(A.temperature=f.temperature),f.topP!==void 0&&(A.topP=f.topP),f.topK!==void 0&&(A.topK=f.topK),f.presencePenalty!==void 0&&(A.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(A.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(A.stopSequences=f.stopSequences),f.endSequences!==void 0&&(A.endSequences=f.endSequences),f.stream!==void 0&&(A.stream=f.stream),f.n!==void 0&&(A.n=f.n);let x={...h};Object.keys(A).length>0&&(x.modelConfig={...h.modelConfig??{},...A});let y=f.thinking?.thinkingTokenBudget;if(typeof y=="number"){let b=u.thinkingTokenBudgetLevels,I=[["minimal",b?.minimal??200],["low",b?.low??800],["medium",b?.medium??5e3],["high",b?.high??1e4],["highest",b?.highest??24500]],T="minimal",v=Number.POSITIVE_INFINITY;for(let[k,R]of I){let C=Math.abs(y-R);C<v&&(v=C,T=k)}x.thinkingTokenBudget=T}return f.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!f.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Ln,defaults:{model:u.model},options:o,supportFor:d,models:m??s})}};function gc(i,e){let t=i.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?s.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):s.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,c=o[l];c&&c.type==="text"&&(o[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=hc(t);return fc(n)}function hc(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function fc(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Ji(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 Dn=(w=>(w.GPT4="gpt-4",w.GPT41="gpt-4.1",w.GPT41Mini="gpt-4.1-mini",w.GPT41Nano="gpt-4.1-nano",w.GPT4O="gpt-4o",w.GPT4OMini="gpt-4o-mini",w.GPT4ChatGPT4O="chatgpt-4o-latest",w.GPT4Turbo="gpt-4-turbo",w.GPT35Turbo="gpt-3.5-turbo",w.GPT35TurboInstruct="gpt-3.5-turbo-instruct",w.GPT35TextDavinci002="text-davinci-002",w.GPT3TextBabbage002="text-babbage-002",w.GPT3TextAda001="text-ada-001",w.GPT5="gpt-5",w.GPT5Nano="gpt-5-nano",w.GPT5Mini="gpt-5-mini",w.GPT5Chat="gpt-5-chat",w.GPT5Pro="gpt-5-pro",w.GPT51="gpt-5.1",w.GPT51ChatLatest="gpt-5.1-chat-latest",w.GPT52="gpt-5.2",w.GPT52ChatLatest="gpt-5.2-chat-latest",w.GPT52Pro="gpt-5.2-pro",w.O1="o1",w.O1Mini="o1-mini",w.O3="o3",w.O3Mini="o3-mini",w.O4Mini="o4-mini",w))(Dn||{}),Bt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Bt||{});var jt=(S=>(S.GPT4="gpt-4",S.GPT41="gpt-4.1",S.GPT41Mini="gpt-4.1-mini",S.GPT41Nano="gpt-4.1-nano",S.GPT4O="gpt-4o",S.GPT4OMini="gpt-4o-mini",S.GPT4ChatGPT4O="chatgpt-4o-latest",S.GPT4Turbo="gpt-4-turbo",S.GPT35Turbo="gpt-3.5-turbo",S.GPT35TurboInstruct="gpt-3.5-turbo-instruct",S.GPT35TextDavinci002="text-davinci-002",S.GPT3TextBabbage002="text-babbage-002",S.GPT3TextAda001="text-ada-001",S.GPT5="gpt-5",S.GPT5Nano="gpt-5-nano",S.GPT5Mini="gpt-5-mini",S.GPT5Chat="gpt-5-chat",S.GPT5Pro="gpt-5-pro",S.GPT51="gpt-5.1",S.GPT51ChatLatest="gpt-5.1-chat-latest",S.GPT52="gpt-5.2",S.GPT52ChatLatest="gpt-5.2-chat-latest",S.GPT52Pro="gpt-5.2-pro",S.O1Pro="o1-pro",S.O1="o1",S.O1Mini="o1-mini",S.O3Pro="o3-pro",S.O3="o3",S.O3Mini="o3-mini",S.O4Mini="o4-mini",S))(jt||{});var qt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],vr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var xc=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},kt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...oe()}),Or=()=>structuredClone({...kt(),model:"gpt-5"}),kr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ce()}),Mr=()=>({...kt(),model:"gpt-5-nano"}),ms=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Ac(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=xc(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...p?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new de(a.message.refusal,e.model,e.id);let l=Yi(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:p,name:d}})=>({id:u,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(p)throw new de(p,void 0,n);let f=Yi(h),A=d?.map(({id:x,index:y,function:{name:b,arguments:I}})=>{typeof x=="string"&&typeof y=="number"&&!s.indexIdMap[y]&&(s.indexIdMap[y]=x);let T=s.indexIdMap[y];return T?{id:T,type:"function",function:{name:b,params:I}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:g?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:A,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Yi=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ac(i){return i.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var fe=class extends Ae{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new ms(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},zt=class extends fe{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...qt,...s??[]];let a=c=>{let u=He({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,p=u?.config;if(!p)return c;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let g={...u};Object.keys(d).length>0&&(g.modelConfig={...u.modelConfig??{},...d});let h=p?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",x=Number.POSITIVE_INFINITY;for(let[y,b]of f){let I=Math.abs(h-b);I<x&&(x=I,A=y)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...kt(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var yc=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},bc=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},gs=kt,Xi=kr,Zi=Mr,ea=Or,Ht=class extends fe{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let c={...gs(),...o},u=yc(r),p=bc(u);l=[...qt,...l??[]];let d=g=>{let h=He({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:p&&(h?.supported?.structuredOutputs??!1),functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Er=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.");Ic(e),this.services=[...e].sort(t?.comparator??i.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new i(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}},t=0,n=0,r=0,o=0;for(let s of this.services){let a=s.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,o+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let s of this.services){let a=s.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,s=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=s}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,s=r?.requiresAudio,a=this.services,l=e.model;if((n||o||s)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||s&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),s&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Oe))throw p;switch(p.constructor){case ft:throw p;case qe:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Ne:break;case ht:break;case Ke:break;case tt:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Oe)||r instanceof qe&&![408,429,500,502,503,504].includes(r.status)||r instanceof ft)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let s=this.getNextService(this.services,n);if(!s.service)throw r;this.currentService=s.service,n=s.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Ic(i){let e=i.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function Mt(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let p of u.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function hs(i,e){let t=i.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Pr(i,e){return i.map(t=>{let n=t.getFeatures(),r=hs(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function Fr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Mt(i),r=Pr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function ta(i,e){let t=Mt(i),n=Pr(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function na(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function ra(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var Gn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Gn||{}),Un=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(Un||{});var _r=[{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 xs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...oe()}),sa=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ce()}),fs=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let s=Tc(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,g]of Object.entries(p.parameters.properties))d[m]={description:g.description,type:g.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:s,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[c,u]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Kt=class extends Ae{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...xs(),...t},s=new fs(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let p={};u.maxTokens!==void 0&&(p.maxTokens=u.maxTokens),u.temperature!==void 0&&(p.temperature=u.temperature),u.topP!==void 0&&(p.topP=u.topP),u.topK!==void 0&&(p.topK=u.topK),u.presencePenalty!==void 0&&(p.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(p.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(p.stopSequences=u.stopSequences),u.endSequences!==void 0&&(p.endSequences=u.endSequences),u.stream!==void 0&&(p.stream=u.stream),u.n!==void 0&&(p.n=u.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:_r,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Tc(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=oa(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=oa(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function oa(i){return i?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var Bn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Bn||{});var Nr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var As=()=>structuredClone({model:"deepseek-chat",...oe()}),ia=()=>structuredClone({model:"deepseek-coder",...Ce()}),Wt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...As(),...t};o=[...Nr,...o??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var jn=(x=>(x.Gemini3Flash="gemini-3-flash-preview",x.Gemini3Pro="gemini-3-pro-preview",x.Gemini3ProImage="gemini-3-pro-image-preview",x.Gemini25Pro="gemini-2.5-pro",x.Gemini25Flash="gemini-2.5-flash",x.Gemini25FlashLite="gemini-2.5-flash-lite",x.Gemini20Flash="gemini-2.0-flash",x.Gemini20FlashLite="gemini-2.0-flash-lite",x.Gemini20ProExp="gemini-2.0-pro-exp-02-05",x.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",x.Gemini1Pro="gemini-1.0-pro",x.Gemini15Flash="gemini-1.5-flash",x.Gemini15Flash002="gemini-1.5-flash-002",x.Gemini15Flash8B="gemini-1.5-flash-8b",x.Gemini15Pro="gemini-1.5-pro",x.GeminiFlashLatest="gemini-flash-latest",x.GeminiFlashLiteLatest="gemini-flash-lite-latest",x.GeminiProLatest="gemini-pro-latest",x))(jn||{}),$r=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))($r||{}),Lr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(Lr||{}),Dr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Dr||{}),ys=(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))(ys||{}),aa=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var Gr=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Ur=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,Ur(n)]))),e.items&&(e.items=Ur(e.items)),e},la=[{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"}],Is=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:la,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...oe()}),ca=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:la,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Ce()}),bs=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let A=r?"&":"?",x=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${A}key=${x}`}let s=e.chatPrompt.filter(A=>A.role==="system").map(A=>A.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(A=>A.role!=="system");for(let A=0;A<c.length;A++){let x=c[A];switch(x.role){case"user":{let y=Array.isArray(x.content)?x.content.map((b,I)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${I})`)}}):[{text:x.content}];l.push({role:"user",parts:y});break}case"assistant":{let y=[],b=x.thoughtBlocks,I=x.functionCalls&&x.functionCalls.length>0,T=b?.[0],v=b?.map(R=>R.data).join("")??"",k=T?.signature;if(v&&y.push({...I?{}:{thought:!0},text:v,...k&&!I?{thought_signature:k}:{}}),x.functionCalls){let R=x.functionCalls.map((C,O)=>{let w;if(typeof C.function.params=="string"){let S=C.function.params;if(S.trim().length===0)w={};else try{w=JSON.parse(S)}catch{throw new Error(`Failed to parse function params JSON: ${S}`)}}else w=C.function.params;let E={functionCall:{name:C.function.name,args:w}};return k&&O===0&&(E.thought_signature=k),E});y.push(...R)}if(x.content&&y.push({text:x.content}),y.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:y});break}case"function":{let y=[],b=x,I=A;for(;;){if(!("functionId"in b))throw new Error(`Chat prompt functionId is empty (index: ${I})`);if(y.push({functionResponse:{name:b.functionId,response:{result:b.result}}}),I+1<c.length&&c[I+1].role==="function")I++,b=c[I];else break}A=I,l.push({role:"user",parts:y});break}default:throw new Error(`Invalid role: ${JSON.stringify(x)} (index: ${A})`)}}let u=[];if(e.functions&&e.functions.length>0){let A=e.functions.map(x=>{let y={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=x.parameters?Ur(x.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...y}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:x.name,description:x.description,parameters:b}});u.push({function_declarations:A})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let A=this.options.googleMaps,x=A?.enableWidget!==void 0?{enableWidget:A.enableWidget}:{};u.push({google_maps:x})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(A=>A&&Array.isArray(A.function_declarations)&&A.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let A=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...A}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let A=this.config.thinkingTokenBudgetLevels,x=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=A?.minimal??200,x&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=A?.low??800,x&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=A?.medium??5e3,x&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=A?.high??1e4,x&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=A?.highest??24500,x&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let A=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=Ur(A)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new de("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new de("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new de("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new de("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new de("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new de("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new de("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new de("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new de("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){s.thought=c.text;let u=c.thoughtSignature||c.thought_signature;s.thoughtBlocks||(s.thoughtBlocks=[]),s.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else s.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!s.thoughtBlocks||s.thoughtBlocks.length===0)s.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=s.thoughtBlocks[s.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}s.functionCalls=[...s.functionCalls??[],{id:ve(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;s.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(s.citations=[...s.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return s});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}};supportsContextCache=e=>{let t=e;return aa.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:s}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!s||s.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),s&&s.length>0&&(a.contents=s);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let o=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${o}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:o=>{let s=o;if(s?.name)return{name:s.name,expiresAt:s.expireTime,tokenCount:s.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,o=e.modelConfig?.stream??this.config.stream,{dynamicContents:s,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:o?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=o?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain"},u=this.config.safetySettings,p={contents:s,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if("cache"in s&&s.cache){r=o;break}}for(let o=0;o<e.length;o++){let s=e[o];if(s.role==="system"){t={role:"user",parts:[{text:s.content}]};continue}if(r>=0&&o<=r)if(s.role==="user"){let a=[];if(typeof s.content=="string")a.push({text:s.content});else if(Array.isArray(s.content))for(let l of s.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else s.role==="assistant"&&s.content&&n.push({role:"model",parts:[{text:s.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if(!("cache"in s&&s.cache))switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else if(r.role==="assistant"){let o=[];if(r.content&&o.push({text:r.content}),r.functionCalls)for(let s of r.functionCalls){let a;if(typeof s.function.params=="string")try{a=JSON.parse(s.function.params)}catch{a={}}else a=s.function.params??{};o.push({functionCall:{name:s.function.name,args:a}})}o.length>0&&n.push({role:"model",parts:o})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},Vt=class i extends Ae{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,u,p;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Is(),...o},m=new bs(d,c,r,e,s);l=[...Gr,...l??[]];let g=f=>{let A=He({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!1,structuredOutputs:A?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:m.supportsContextCache(f),types:["persistent"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let A=f,x=A?.config;if(!x)return f;let y={};x.maxTokens!==void 0&&(y.maxTokens=x.maxTokens),x.temperature!==void 0&&(y.temperature=x.temperature),x.topP!==void 0&&(y.topP=x.topP),x.topK!==void 0&&(y.topK=x.topK),x.presencePenalty!==void 0&&(y.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(y.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(y.stopSequences=x.stopSequences),x.endSequences!==void 0&&(y.endSequences=x.endSequences),x.stream!==void 0&&(y.stream=x.stream),x.n!==void 0&&(y.n=x.n);let b={...A};Object.keys(y).length>0&&(b.modelConfig={...A.modelConfig??{},...y});let I=x.thinking?.thinkingTokenBudget;if(typeof I=="number"){let T=d.thinkingTokenBudgetLevels,v=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],k="minimal",R=Number.POSITIVE_INFINITY;for(let[C,O]of v){let w=Math.abs(I-O);w<R&&(R=w,k=C)}b.thinkingTokenBudget=k}return x.thinking?.includeThoughts!==void 0&&(b.showThoughts=!!x.thinking.includeThoughts),b});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:h??a})}};var Cc=new $e,Jt=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(Cc.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var qn=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(qn||{});var Br=[{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 Rc=()=>structuredClone({model:"llama-3.3-70b-versatile",...oe()}),Qt=class extends fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...Rc(),...t},a={...n,streamingUsage:!1};o=[...Br,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new Jt(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var jr=[];var qr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(qr||{});var Cs=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...oe()}),ua=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ce()}),Ts=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
|
|
170
170
|
${JSON.stringify(e.functions,null,2)}
|
|
171
171
|
`:"",r=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let c=l.functionCalls?.map(u=>{let p=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${p})`}).join(`
|
|
172
172
|
`);return c?`Assistant: ${l.content}
|
|
@@ -200,21 +200,21 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
|
|
|
200
200
|
|
|
201
201
|
`,o+=c.length)}else r=`${s}
|
|
202
202
|
|
|
203
|
-
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Mc=(i,e=.1)=>{let t=[...i].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var xn=require("@opentelemetry/api");var Xn=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:s}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(c=>c.index===s);if(!l){a.chat.push({index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(Array.isArray(o)&&o.length>0){let c=l.value.thoughtBlocks??[];for(let u of o){let p=c.length>0?c[c.length-1]:void 0;!u.signature&&u.data?p&&!p.signature?(p.data=(p.data??"")+u.data,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):u.signature?p&&!p.signature?(p.data=(p.data??"")+u.data,p.signature=u.signature,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):c.length===0&&c.push(structuredClone(u))}l.value.thoughtBlocks=c,c.length>0&&(l.value.thought=c.map(u=>u.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(s=>s.index===e).map(s=>s.value):o=r.find(s=>s.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(s=>({...s,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},pn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Xn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Xn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Lt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Sr(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Xn):this.defaultMemory.reset()}};var ct=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},so=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ct({message:o});if(!o)throw r?new ct({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Ns=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(s=>s.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let s of r){let{message:a,fn:l}=s,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new ct({message:c});if(!c&&a)throw new ct({message:a})}}};var $s={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Zn,Ds=i=>{if(Zn)return Zn;let e=i??W.meter;if(e)return Zn=Ec(e),Zn};var Ca=()=>{let i=[];return W.meter||i.push("Global meter not initialized"),!Zn&&W.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},Ec=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"})}),io=$s,Ra=i=>{io={...io,...i}},wa=()=>({...io}),st=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=io.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e};var Sa=(i,e,t,n,r,o,s)=>{try{let a=st({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{},...s});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,a),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,a),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},ao=(i,e,t,n,r)=>{try{let o=st({...n?{signature:n}:{},...r});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)}},Ls=(i,e,t,n)=>{try{let r=st({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,r),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},va=(i,e,t)=>{try{let n=st({error_type:"refusal",...e?{signature:e}:{},...t});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},Gs=(i,e,t,n,r,o)=>{try{let s=st({success:t.toString(),...r?{signature:r}:{},...o});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,s),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,s),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,s),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,s))}catch(s){console.warn("Failed to record error correction metric:",s)}},Oa=(i,e,t,n,r=!1,o,s)=>{try{let a=st({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{},...s});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,a),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,a),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,a),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},ka=(i,e,t,n,r)=>{try{let o=st({...n?{signature:n}:{},...r});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)}},Ma=(i,e,t,n,r,o)=>{try{let s=st({is_streaming:e.toString(),...r?{signature:r}:{},...o});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,s),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,s),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,s)}catch(s){console.warn("Failed to record streaming metric:",s)}},Ea=(i,e,t,n,r,o)=>{try{let s=st({result_picker_used:t.toString(),...r?{signature:r}:{},...o});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,s),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,s),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,s)}catch(s){console.warn("Failed to record samples metric:",s)}},Pa=(i,e,t,n,r,o,s)=>{try{let a=st({...o?{signature:o}:{},...s});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,a),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,a),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,a),i.demosUsedGauge&&i.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},lo=(i,e,t,n,r)=>{try{let o=st({metric_type:e,...n?{signature:n}:{},...r});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 dn=i=>{let e=(()=>{switch(i?.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";case"object":return"object";default:return"string"}})();return i?.isArray?`array of ${e}s`:e},Se=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Fa=i=>{let t=i.map(n=>`'${n.title}' (${dn(n.type)})`).join(", ");return new Se(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${i[0]?.title}:") and then provide a valid ${dn(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},co=i=>new Se(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${dn(i.type)} value directly after.`);var uo=i=>new Se(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${dn(i.type)}. Do not use null, undefined, or leave it blank.`),_a=(i,e)=>new Se(`Invalid JSON: ${e} in field '${i.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),Na=(i,e)=>new Se(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${dn(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),$a=(i,e,t)=>new Se(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${dn(i.type)}. Ensure formatting exactly matches the expected type.`),Da=(i,e,t)=>new Se(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),La=(i,e,t)=>new Se(`Invalid date/time for '${i.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Us=(i,e,t)=>new Se(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),mn=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new Se(r)},Bs=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new Se(r)};var Ga=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";Ri(i,e,c,n)}return r&&Ls(r,"validation",o,a),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},Ua=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";wi(i,e,c,n)}return r&&Ls(r,"assertion",o,a),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},Ba=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{t&&n&&Si(i,e,n),r&&va(r,o,a),s&&s.addEvent("refusal.error",{message:i.toString()})};function ja(i,e){if(!e)return i;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return i;let n=t.join(". ");return!i||i.trim().length===0?n:`${i.trim().endsWith(".")?i.trim():`${i.trim()}.`} ${n}`}function go(i,e="Schema"){if("name"in i&&"type"in i)return po(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let o=po(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function po(i,e=!1){let t=i.type,n=ja(i.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${i.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.items.properties[o]=po(a,!0),s.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=ja(t.description||i.description,t);r.items={type:qa(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.properties[o]=po(a,!0),s.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=qa(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function qa(i){switch(i){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function mo(i){if(!i||typeof i!="object")throw new Error("Schema must be an object");if(i.type==="array"){if(!i.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');mo(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))mo(e)}var Et=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},er=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
203
|
+
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Mc=(i,e=.1)=>{let t=[...i].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var xn=require("@opentelemetry/api");var Xn=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:s}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(c=>c.index===s);if(!l){a.chat.push({index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(Array.isArray(o)&&o.length>0){let c=l.value.thoughtBlocks??[];for(let u of o){let p=c.length>0?c[c.length-1]:void 0;!u.signature&&u.data?p&&!p.signature?(p.data=(p.data??"")+u.data,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):u.signature?p&&!p.signature?(p.data=(p.data??"")+u.data,p.signature=u.signature,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):c.length===0&&c.push(structuredClone(u))}l.value.thoughtBlocks=c,c.length>0&&(l.value.thought=c.map(u=>u.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(s=>s.index===e).map(s=>s.value):o=r.find(s=>s.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(s=>({...s,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},pn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Xn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Xn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Dt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Sr(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Xn):this.defaultMemory.reset()}};var ct=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},so=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ct({message:o});if(!o)throw r?new ct({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Ns=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(s=>s.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let s of r){let{message:a,fn:l}=s,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new ct({message:c});if(!c&&a)throw new ct({message:a})}}};var $s={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Zn,Ls=i=>{if(Zn)return Zn;let e=i??W.meter;if(e)return Zn=Ec(e),Zn};var Ca=()=>{let i=[];return W.meter||i.push("Global meter not initialized"),!Zn&&W.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},Ec=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"})}),io=$s,Ra=i=>{io={...io,...i}},wa=()=>({...io}),st=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=io.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e};var Sa=(i,e,t,n,r,o,s)=>{try{let a=st({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{},...s});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,a),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,a),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},ao=(i,e,t,n,r)=>{try{let o=st({...n?{signature:n}:{},...r});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)}},Ds=(i,e,t,n)=>{try{let r=st({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,r),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},va=(i,e,t)=>{try{let n=st({error_type:"refusal",...e?{signature:e}:{},...t});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},Gs=(i,e,t,n,r,o)=>{try{let s=st({success:t.toString(),...r?{signature:r}:{},...o});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,s),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,s),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,s),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,s))}catch(s){console.warn("Failed to record error correction metric:",s)}},Oa=(i,e,t,n,r=!1,o,s)=>{try{let a=st({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{},...s});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,a),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,a),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,a),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},ka=(i,e,t,n,r)=>{try{let o=st({...n?{signature:n}:{},...r});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)}},Ma=(i,e,t,n,r,o)=>{try{let s=st({is_streaming:e.toString(),...r?{signature:r}:{},...o});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,s),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,s),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,s)}catch(s){console.warn("Failed to record streaming metric:",s)}},Ea=(i,e,t,n,r,o)=>{try{let s=st({result_picker_used:t.toString(),...r?{signature:r}:{},...o});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,s),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,s),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,s)}catch(s){console.warn("Failed to record samples metric:",s)}},Pa=(i,e,t,n,r,o,s)=>{try{let a=st({...o?{signature:o}:{},...s});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,a),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,a),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,a),i.demosUsedGauge&&i.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},lo=(i,e,t,n,r)=>{try{let o=st({metric_type:e,...n?{signature:n}:{},...r});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 dn=i=>{let e=(()=>{switch(i?.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";case"object":return"object";default:return"string"}})();return i?.isArray?`array of ${e}s`:e},Se=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Fa=i=>{let t=i.map(n=>`'${n.title}' (${dn(n.type)})`).join(", ");return new Se(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${i[0]?.title}:") and then provide a valid ${dn(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},co=i=>new Se(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${dn(i.type)} value directly after.`);var uo=i=>new Se(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${dn(i.type)}. Do not use null, undefined, or leave it blank.`),_a=(i,e)=>new Se(`Invalid JSON: ${e} in field '${i.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),Na=(i,e)=>new Se(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${dn(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),$a=(i,e,t)=>new Se(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${dn(i.type)}. Ensure formatting exactly matches the expected type.`),La=(i,e,t)=>new Se(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Da=(i,e,t)=>new Se(`Invalid date/time for '${i.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Us=(i,e,t)=>new Se(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),mn=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new Se(r)},Bs=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new Se(r)};var Ga=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";Ri(i,e,c,n)}return r&&Ds(r,"validation",o,a),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},Ua=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";wi(i,e,c,n)}return r&&Ds(r,"assertion",o,a),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},Ba=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s,customLabels:a})=>{t&&n&&Si(i,e,n),r&&va(r,o,a),s&&s.addEvent("refusal.error",{message:i.toString()})};function ja(i,e){if(!e)return i;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return i;let n=t.join(". ");return!i||i.trim().length===0?n:`${i.trim().endsWith(".")?i.trim():`${i.trim()}.`} ${n}`}function go(i,e="Schema"){if("name"in i&&"type"in i)return po(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let o=po(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function po(i,e=!1){let t=i.type,n=ja(i.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${i.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.items.properties[o]=po(a,!0),s.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=ja(t.description||i.description,t);r.items={type:qa(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.properties[o]=po(a,!0),s.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=qa(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function qa(i){switch(i){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function mo(i){if(!i||typeof i!="object")throw new Error("Schema must be an object");if(i.type==="array"){if(!i.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');mo(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))mo(e)}var Et=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},er=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
204
204
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},tr=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
|
|
205
205
|
${t.join(`
|
|
206
206
|
`)}`};toString(){return[`${this.name}: Function execution error in '${this.func.name}'`,...this.fields.map(t=>{let n=this.getFieldDescription(t.field);return` - ${t.field}: ${t.message}${n?` (${n})`:""}`}),this.funcId?` Function ID: ${this.funcId}`:""].join(`
|
|
207
207
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},nr=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;e.parameters?s=e.func.length===2?await e.func(r,o):await e.func(r):s=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??W.functionResultFormatter)(s);return{formatted:String(l),rawResult:s,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(s=>s.name===e.name);if(o||(o=this.funcList.find(s=>n(s.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(s){throw s instanceof er?new tr(s.getFields(),o,e.id):s}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},ho=(i,e)=>{if(i.length===0)return[...e??[]];let t=i.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{mo(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
|
|
208
208
|
${r.message}
|
|
209
|
-
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},fo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d})=>{let m=new nr(e),g=new Set,h=[],f=b=>{let I=k=>k.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),T=I(b),v=e.find(k=>k.name===b);return v||(v=e.find(k=>I(k.name)===T)),v},A=t.map(b=>{if(!b.id)throw new Error(`Function ${b.name} did not return an ID`);let I=i.getOptions().tracer??W.tracer;return I?I.startActiveSpan(`Tool: ${b.name}`,async T=>{try{T?.setAttributes?.({"tool.name":b.name,"tool.mode":"native","function.id":b.id,"session.id":r??""});let{formatted:v,rawResult:k,parsedArgs:R}=await m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:c,traceId:T?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let C=f(b.name);C&&h.push({func:C,args:R,result:k})}if(a?T.addEvent("gen_ai.tool.message",{name:b.name}):T.addEvent("gen_ai.tool.message",{name:b.name,args:b.args,result:v??""}),s){let C={name:b.name};a||(C.args=b.args,C.result=v??""),s.addEvent("function.call",C)}return{result:v??"",role:"function",functionId:b.id,index:l}}catch(v){if(T?.recordException?.(v),v instanceof tr){let k=v.getFixingInstructions(),R={name:b.name,message:v.toString()};return a||(R.args=b.args,R.fixing_instructions=k),T?.addEvent?.("function.error",R),p&&ss(v,l,k,u),{functionId:b.id,isError:!0,index:l,result:k,role:"function"}}throw v}finally{T?.end?.()}}):m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:c,traceId:o,stopFunctionNames:d}).then(({formatted:T,rawResult:v,parsedArgs:k})=>{if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let R=f(b.name);R&&h.push({func:R,args:k,result:v})}if(s){let R={name:b.name};a||(R.args=b.args,R.result=T??""),s.addEvent("function.call",R)}return{result:T??"",role:"function",functionId:b.id,index:l}}).catch(T=>{if(!(T instanceof tr))throw T;let v=T.getFixingInstructions();if(s){let k={name:b.name,message:T.toString()};a||(k.args=b.args,k.fixing_instructions=v),s.addEvent("function.error",k)}return p&&ss(T,l,v,u),{functionId:b.id,isError:!0,index:l,result:v,role:"function"}})}),y=(await Promise.all(A)).map(b=>b.result===void 0||b.result===""?{...b,result:"done"}:b);if(n.addFunctionResults(y,r),p){let b=y.filter(I=>!I.isError);b.length>0&&Ci(b,u)}if(h.length>0)throw new Et(h);return g};function js(i,e,t,n){if(!e||e.length===0)return;if(!i.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function za(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}function Ha(i){if(!i.trim())return null;try{return JSON.parse(i)}catch{}let e=Pc(i);try{return JSON.parse(e)}catch{return null}}function Pc(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1));e.match(/[0-9][eE.+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r){r=!1;continue}if(s==="\\"){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"?t.push("}"):s==="["?t.push("]"):s==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():s==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}var Rt=Pn(require("dayjs"),1),Ka=Pn(require("dayjs/plugin/customParseFormat.js"),1),Wa=Pn(require("dayjs/plugin/timezone.js"),1),Va=Pn(require("dayjs/plugin/utc.js"),1);Rt.default.extend(Va.default);Rt.default.extend(Wa.default);Rt.default.extend(Ka.default);function Ja(i,e,t=!1){try{return Fc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw
|
|
209
|
+
Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},fo=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d})=>{let m=new nr(e),g=new Set,h=[],f=b=>{let I=k=>k.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),T=I(b),v=e.find(k=>k.name===b);return v||(v=e.find(k=>I(k.name)===T)),v},A=t.map(b=>{if(!b.id)throw new Error(`Function ${b.name} did not return an ID`);let I=i.getOptions().tracer??W.tracer;return I?I.startActiveSpan(`Tool: ${b.name}`,async T=>{try{T?.setAttributes?.({"tool.name":b.name,"tool.mode":"native","function.id":b.id,"session.id":r??""});let{formatted:v,rawResult:k,parsedArgs:R}=await m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:c,traceId:T?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let C=f(b.name);C&&h.push({func:C,args:R,result:k})}if(a?T.addEvent("gen_ai.tool.message",{name:b.name}):T.addEvent("gen_ai.tool.message",{name:b.name,args:b.args,result:v??""}),s){let C={name:b.name};a||(C.args=b.args,C.result=v??""),s.addEvent("function.call",C)}return{result:v??"",role:"function",functionId:b.id,index:l}}catch(v){if(T?.recordException?.(v),v instanceof tr){let k=v.getFixingInstructions(),R={name:b.name,message:v.toString()};return a||(R.args=b.args,R.fixing_instructions=k),T?.addEvent?.("function.error",R),p&&ss(v,l,k,u),{functionId:b.id,isError:!0,index:l,result:k,role:"function"}}throw v}finally{T?.end?.()}}):m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:c,traceId:o,stopFunctionNames:d}).then(({formatted:T,rawResult:v,parsedArgs:k})=>{if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let R=f(b.name);R&&h.push({func:R,args:k,result:v})}if(s){let R={name:b.name};a||(R.args=b.args,R.result=T??""),s.addEvent("function.call",R)}return{result:T??"",role:"function",functionId:b.id,index:l}}).catch(T=>{if(!(T instanceof tr))throw T;let v=T.getFixingInstructions();if(s){let k={name:b.name,message:T.toString()};a||(k.args=b.args,k.fixing_instructions=v),s.addEvent("function.error",k)}return p&&ss(T,l,v,u),{functionId:b.id,isError:!0,index:l,result:v,role:"function"}})}),y=(await Promise.all(A)).map(b=>b.result===void 0||b.result===""?{...b,result:"done"}:b);if(n.addFunctionResults(y,r),p){let b=y.filter(I=>!I.isError);b.length>0&&Ci(b,u)}if(h.length>0)throw new Et(h);return g};function js(i,e,t,n){if(!e||e.length===0)return;if(!i.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function za(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}function Ha(i){if(!i.trim())return null;try{return JSON.parse(i)}catch{}let e=Pc(i);try{return JSON.parse(e)}catch{return null}}function Pc(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1));e.match(/[0-9][eE.+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r){r=!1;continue}if(s==="\\"){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"?t.push("}"):s==="["?t.push("]"):s==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():s==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}var Rt=Pn(require("dayjs"),1),Ka=Pn(require("dayjs/plugin/customParseFormat.js"),1),Wa=Pn(require("dayjs/plugin/timezone.js"),1),Va=Pn(require("dayjs/plugin/utc.js"),1);Rt.default.extend(Va.default);Rt.default.extend(Wa.default);Rt.default.extend(Ka.default);function Ja(i,e,t=!1){try{return Fc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw La(i,e,r)}}function Fc(i){if(!(0,Rt.default)(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Rt.default.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Qa(i,e,t=!1){try{return _c(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Da(i,e,r)}}function _c(i){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=i.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=Rt.default.tz(n,o,r);if(!s.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return s.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Ya=i=>(0,Rt.default)(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Dg=new $e,xo=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(c,u)=>{switch(c){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";case"object":return typeof u=="object";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(i.type?.name==="image"){let c;if(Array.isArray(e)){for(let u of e)if(!r(u)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let o=c=>!(!c||typeof c!="object"||!("data"in c));if(i.type?.name==="audio"){let c;if(Array.isArray(e)){for(let u of e)if(!o(u)){c="object ({ data: string; format?: string })";break}}else o(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let u="data"in c,p="fileUri"in c;return!(!u&&!p||u&&p)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let u of e)if(!s(u)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(i.type?.name==="url"){let c;if(Array.isArray(e)){for(let u of e)if(!a(u)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let c of e)if(!n(t.name,c)){l=!1;break}}else l=n(t.name,e);if(!l){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function rr(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let s=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(s.push(c),l.add(c.url));r.citations=s}}}return Object.values(e)}var Xa=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
|
|
210
210
|
`),r=[];for(let o of n){let s=o.trim();if(s){if(s[0]&&e.has(s[0]))r.push(s.slice(1).trim());else if(t.test(s))r.push(s.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function zs(i,e){let{index:t,delta:n,version:r}=e,o=i.find(a=>a.index===t)?.delta;if(!o)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=o[a],c=n[a];l===void 0&&Array.isArray(c)?o[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?o[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?o[a]=`${l??""}${c}`:o[a]=c}let s=i.find(a=>a.index===t);return s&&(s.version=r),i}var qs=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)}},Nc=new qs(500);function Za(i,e,t=0,n=Nc){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let r=i.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let s=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}function wt(i,e){if(typeof i!="string")throw Us(e,String(i),"URL must be a string");try{new URL(i)}catch{throw Us(e,i,"Invalid URL format. Expected a valid URL like https://example.com")}}function Je(i,e){if(typeof i!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&i.length<t.minLength)throw mn(e,i,"minLength",t.minLength);if(t.maxLength!==void 0&&i.length>t.maxLength)throw mn(e,i,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(i))throw mn(e,i,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw mn(e,i,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(i)}catch{throw mn(e,i,"format","valid URL")}}}function Qe(i,e){if(typeof i!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&i<t.minimum)throw Bs(e,i,"minimum",t.minimum);if(t.maximum!==void 0&&i>t.maximum)throw Bs(e,i,"maximum",t.maximum)}}var bo=(i,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Ws(i,e,a,t,{strictMode:r,skipEarlyFail:s,treatAllFieldsOptional:o}),Vs(i,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},Hs=(i,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw Fa(n)},Ws=(i,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let s=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=s.map((g,h)=>({field:g,index:h})).filter(({index:g})=>!l.has(g)),u,p,d=-1,m=0;for(let{index:g,field:h}of c){let A=`${(t.extractedFields.length===0?"":`
|
|
211
211
|
`)+h.title}:`,x=Za(n,A,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=A.length,u=g,p=h)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(h=>!h.isOptional);if(g)throw co(g)}break}if(a&&p&&a.name!==p.name)throw co(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),h=Ao(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,p!==void 0&&u!==void 0&&(t.currField=p,t.currFieldIndex=u),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Vs=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=i.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let g=`
|
|
212
212
|
${m.title}:`,h=n.indexOf(g,t.s);h!==-1&&h<c&&(c=h)}let p=n.substring(t.s,c).trim(),d=Ao(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw co(p)}if($c(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Hs(t,e,i.getOutputFields()):c||Hs(t,e,i.getOutputFields())}},$c=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let s=r[0];if(s){let a=`${s.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
|
|
213
213
|
${s.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=Ao(s,d);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
|
|
214
|
-
`);for(let s of r){if(s.name in e)continue;let a=`${s.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let p=Ao(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},el=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Ks(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 Ja(i,e,t);case"datetime":return Qa(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*tl(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=p?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[s]:h}},r.streamedIndex[s]=u+g.length)}function*Js(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*tl(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*tl(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function Ao(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw uo(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=Ks(e);return t=JSON.parse(r),t}catch(r){throw _a(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Xa(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Na(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=Ks(s);s=JSON.parse(a)}catch{}t[r]=el(i,s,!0)}}else t=el(i,e)}catch(r){throw $a(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&wt(t,i),(n.name==="string"||n.name==="code")&&Je(t,i),n.name==="number"&&Qe(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Je(r,i):n.name==="number"&&Qe(r,i));return t}function Io(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw uo(r);continue}let s=r.type;if(s){if(s.name==="url"&&wt(o,r),(s.name==="string"||s.name==="code")&&Je(o,r),s.name==="number"&&Qe(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?wt(a,r):s.name==="string"||s.name==="code"?Je(a,r):s.name==="number"&&Qe(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&yo(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&yo(r,a,t)}}}function yo(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw uo(s);continue}let l=s.type;if(l){if(l.name==="url"&&wt(a,s),(l.name==="string"||l.name==="code")&&Je(a,s),l.name==="number"&&Qe(a,s),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?wt(c,s):l.name==="string"||l.name==="code"?Je(c,s):l.name==="number"&&Qe(c,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&yo(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&yo(s,c,t)}}}var Ks=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Qs(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});nl(r.field,t,s,n)}}async function Ys(i,e,t,n,r,o,s=!1){for(let a of i){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let c=a.process,u=await c(l,{sessionId:o,values:r,done:s});nl(t.currField,n,u,o)}}var nl=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=
|
|
214
|
+
`);for(let s of r){if(s.name in e)continue;let a=`${s.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let p=Ao(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},el=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Ks(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 Ja(i,e,t);case"datetime":return Qa(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*tl(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=p?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[s]:h}},r.streamedIndex[s]=u+g.length)}function*Js(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*tl(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*tl(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function Ao(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw uo(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=Ks(e);return t=JSON.parse(r),t}catch(r){throw _a(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Xa(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Na(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=Ks(s);s=JSON.parse(a)}catch{}t[r]=el(i,s,!0)}}else t=el(i,e)}catch(r){throw $a(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&wt(t,i),(n.name==="string"||n.name==="code")&&Je(t,i),n.name==="number"&&Qe(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Je(r,i):n.name==="number"&&Qe(r,i));return t}function Io(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw uo(r);continue}let s=r.type;if(s){if(s.name==="url"&&wt(o,r),(s.name==="string"||s.name==="code")&&Je(o,r),s.name==="number"&&Qe(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?wt(a,r):s.name==="string"||s.name==="code"?Je(a,r):s.name==="number"&&Qe(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&yo(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&yo(r,a,t)}}}function yo(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw uo(s);continue}let l=s.type;if(l){if(l.name==="url"&&wt(a,s),(l.name==="string"||l.name==="code")&&Je(a,s),l.name==="number"&&Qe(a,s),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?wt(c,s):l.name==="string"||l.name==="code"?Je(c,s):l.name==="number"&&Qe(c,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&yo(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&yo(s,c,t)}}}var Ks=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Qs(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});nl(r.field,t,s,n)}}async function Ys(i,e,t,n,r,o,s=!1){for(let a of i){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let c=a.process,u=await c(l,{sessionId:o,values:r,done:s});nl(t.currField,n,u,o)}}var nl=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=Lc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Lc(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*rl({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let p=u;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.thoughtBlocks||d.thoughtBlocks.length===0)&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*Dc({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Gc({...r,state:c,debug:n});if(s){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());s.citations=c}if(e.push(s),n&&r.logger){let c=structuredClone(s);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*Dc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)Cr(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let h=Ha(s.content);if(h&&typeof h=="object"){let f={},A={};for(let x of Object.keys(h))if(d.some(y=>y.name===x)){let y=h[x],b=s.values[x];if(A[x]=y,typeof y=="string"&&typeof b=="string"&&y.startsWith(b)){let I=y.slice(b.length);I&&(f[x]=I)}else Array.isArray(y)&&Array.isArray(b)?y.length>b.length&&(f[x]=y.slice(b.length)):JSON.stringify(y)!==JSON.stringify(b)&&(f[x]=y)}try{Io(a,A,{allowMissingRequired:!0})}catch{}Object.assign(s.values,A),Object.keys(f).length>0&&(yield{index:i.index,delta:f});return}}if(Ws(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await Ns(u,s.xstate,s.content),l.length!==0&&await Ys(l,s.content,s.xstate,e,s.values,t),yield*Js(a,s.content,s.values,s.xstate,i.index),await so(p,s.values)}else i.thought&&i.thought.length>0?(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
215
215
|
Content: ${s.content}`)}async function*Gc({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,signatureToolCallingManager:f,logger:A,debug:x,stopFunctionNames:y}){let b=f?void 0:js(t,i.functionCalls,i.values,n);if(b){if(!r)throw new Error("Functions are not defined");let I=await fo({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:A,debug:x,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...I]),i.functionCalls=[]}else{let I=e.getOutputFields(),T=e.hasComplexFields(),v=!1;if(T)try{let k=JSON.parse(i.content),R={};for(let C of Object.keys(k))if(I.some(O=>O.name===C)){let O=k[C],w=i.values[C];if(typeof O=="string"&&typeof w=="string"&&O.startsWith(w)){let E=O.slice(w.length);E&&(R[C]=E)}else Array.isArray(O)&&Array.isArray(w)?O.length>w.length&&(R[C]=O.slice(w.length)):JSON.stringify(O)!==JSON.stringify(w)&&(R[C]=O)}try{Io(e,R,{allowMissingRequired:!0})}catch(C){let O=(C.message||"").toLowerCase();if(O.includes("at least")||O.includes("at most")||O.includes("must match pattern")||O.includes("invalid url")||O.includes("required")||O.includes("missing")||O.includes("valid email")||O.includes("number must be"))throw C}Object.assign(i.values,R),yield{index:i.index,delta:R},v=!0}catch(k){let R=(k.message||"").toLowerCase();if(R.includes("at least")||R.includes("at most")||R.includes("must match pattern")||R.includes("invalid url")||R.includes("required")||R.includes("missing")||R.includes("valid email")||R.includes("number must be"))throw k}if(!v){let k=f!==void 0;Vs(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:k,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(f){let k=await f.processResults(i.values);if(k&&k.length>0){if(!r)throw new Error("Functions are not defined");let R=await fo({ai:t,functionList:r,functionCalls:k,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:h,logger:A,debug:x,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...R]),o.updateResult({name:void 0,content:i.content,functionCalls:k.map(C=>({id:C.id,type:"function",function:{name:C.name,params:C.args}})),index:i.index},s);return}}await Ns(p,i.xstate,i.content,!0),await so(d,i.values),m.length&&await Qs(m,i.values,o,s),g.length!==0&&await Ys(g,i.content,i.xstate,o,i.values,s,!0),yield*Js(e,i.content,i.values,i.xstate,i.index)}}async function*ol({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:f,debug:A,signatureToolCallingManager:x,stopFunctionNames:y,disableMemoryCleanup:b}){let I=e.results??[],T=x!==void 0;t.addResponse(I,n);let v=[];for(let O of I)if(Array.isArray(O?.citations))for(let w of O.citations)w?.url&&v.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let O of I){let w=l[O.index];if(!w)throw new Error(`No state found for result (index: ${O.index})`);if(e.modelUsage){let E=Array.from(new Map(v.filter(F=>F.url).map(F=>[F.url,F])).values()),S={...e.modelUsage,...E.length?{citations:E}:{}};if(c.push(S),A&&f){let F=structuredClone(S);delete F.citations,f({name:"ChatResponseUsage",value:F}),S.citations&&S.citations.length>0&&f({name:"ChatResponseCitations",value:S.citations})}}if(x&&O.content){O.thought&&O.thought.length>0&&(w.values[m]=O.thought),bo(g,w.values,O.content,{strictMode:a,treatAllFieldsOptional:T});let S=(await x.processResults(w.values))?.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}}));S&&S.length>0&&t.updateResult({name:O.name,content:O.content,functionCalls:S,index:O.index},n)}if(O.functionCalls?.length){let E=js(i,O.functionCalls,w.values);if(E&&E.length>0){if(!o)throw new Error("Functions are not defined");let S;try{S=await fo({ai:i,functionList:o,functionCalls:E,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:u,index:O.index,functionResultFormatter:h,logger:f,debug:A,stopFunctionNames:y})}catch(F){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),F}w.functionsExecuted=new Set([...w.functionsExecuted,...S])}}else if(O.content){O.thought&&O.thought.length>0&&(w.values[m]=O.thought);let E=g.getOutputFields();if(g.hasComplexFields())try{let F=JSON.parse(O.content),$={};for(let M of Object.keys(F))E.some(P=>P.name===M)&&($[M]=F[M]);Io(g,$),Object.assign(w.values,$)}catch(F){let $=F instanceof SyntaxError;if((F.name?.includes("ValidationError")||F.name?.includes("Error"))&&!$){let P=(F.message||"").toLowerCase();if(P.includes("at least")||P.includes("at most")||P.includes("must match pattern")||P.includes("invalid url")||P.includes("required")||P.includes("missing")||P.includes("valid email")||P.includes("number must be"))throw F}if($)bo(g,w.values,O.content,{strictMode:a,treatAllFieldsOptional:T});else throw F}else bo(g,w.values,O.content,{strictMode:a,treatAllFieldsOptional:T})}if(await so(p,w.values),b||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Qs(d,w.values,t,n),O.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
216
216
|
Content: ${O.content}`)}let k=l.map(O=>O.values);for(let O of k)for(let w of g.getOutputFields())w.isInternal&&delete O[w.name];let R=g.getOutputFields(),C=k.map((O,w)=>{let E={};for(let S of R)S.isInternal||(E[S.name]=O[S.name]);return O[m]!==void 0&&(E[m]=O[m]),{index:w,delta:E}});for(let O of C)yield O}function sl(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[o,s]of t.entries()){let a=e?Array.from(e).some(p=>s.functionsExecuted.has(p)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",u=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var gn=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 q=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Xs=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new q("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 q("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 q('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new q(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof q)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new q(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new q(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new q(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new q(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new q("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new q("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
|
|
217
|
-
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new q(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof q?r:new q(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new q(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof q?r:new q(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new q(`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 q(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof q?o:new q(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new q(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new q(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new q(`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 q(`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 q(`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 q(`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 q?s:new q(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(W.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 q(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new q(`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 q(`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 q(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new q(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 q("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 q(`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 q(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(o,Math.min(this.position,o+20));throw new q(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new q(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function il(i){return new Xs(i).parse()}var or=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Zs(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Zs(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new ge(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Re=class i{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}cache(){return new i({...this,isCached:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},le=Object.assign(()=>new or,{string:i=>new Re({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),number:i=>new Re({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),boolean:i=>new Re({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),json:i=>new Re({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),datetime:i=>new Re({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),date:i=>new Re({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),class:(i,e)=>new Re({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:i=>new Re({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),audio:i=>new Re({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),file:i=>new Re({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),url:i=>new Re({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),email:i=>new Re({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(i,e)=>new Re({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1,isCached:!1}),object:(i,e)=>new Re({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function Zs(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,Zs(t)])):void 0}}function To(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var L=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ge=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=il(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new L(`Invalid Signature: ${n.message}`,void 0,r)}throw new L(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof i)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new L("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 L("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 L?t:new L(`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 L("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 L("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 L("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 L("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);ut(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new L(`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 L(`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 L?t:new L(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ut(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new L(`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 L(`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 L?t:new L(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new L("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ut(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof L?t:new L(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new L("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ut(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof L?t:new L(`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,...To(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...To(t)},o=n.parseField(r);ut(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new L(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new L(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...To(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...To(t)},o=n.parseField(r);ut(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new L(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new L(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ut(e,"input")}),this.getOutputFields().forEach(e=>{ut(e,"output")}),this.sigHash=_e("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ll(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof L?e:new L(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ut(e,"input")}),this.getOutputFields().forEach(e=>{ut(e,"output")}),this.validateSignatureConsistency(),this.sigHash=_e("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ll(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof L?e:new L(`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 L(`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 L(`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 L(`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 L("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new L("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return go(e,this.description??"Schema")}};function al(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 ll(i,e,t){let n=i?`"${i}" `:"",r=e.map(al).join(", "),o=t.map(al).join(", ");return`${n}${r} -> ${o}`}function Uc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ut(i,e){if(!i.name||i.name.length===0)throw new L("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Uc(i.name))throw new L(`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(W.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 L(`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 L(`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 L(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Bc(i,e)}function Bc(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new L(`${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 L("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 L("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new L("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new L(`Invalid class option "${o}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new L("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new L("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 L("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&ei(t.fields,i.name,e)}function ei(i,e,t,n=1){for(let[r,o]of Object.entries(i)){let s=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new L(`${o.type} type is not allowed in nested object fields`,s,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&ei(o.fields,s,t,n+1),o.isArray&&o.fields&&ei(o.fields,`${s}[]`,t,n+1)}}var St=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ge(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new gn,this.key={id:this.signature.hash()}}getSignature(){return new ge(this.signature)}setSignature(e){this.signature=new ge(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of o){let c=s[l.name];c!==void 0&&(xo(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return rr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var cl=`
|
|
217
|
+
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new q(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof q?r:new q(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new q(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof q?r:new q(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new q(`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 q(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof q?o:new q(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new q(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new q(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new q(`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 q(`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 q(`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 q(`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 q?s:new q(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(W.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 q(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new q(`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 q(`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 q(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new q(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 q("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 q(`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 q(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(o,Math.min(this.position,o+20));throw new q(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new q(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function il(i){return new Xs(i).parse()}var or=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Zs(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Zs(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new ge(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Re=class i{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}cache(){return new i({...this,isCached:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},le=Object.assign(()=>new or,{string:i=>new Re({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),number:i=>new Re({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),boolean:i=>new Re({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),json:i=>new Re({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),datetime:i=>new Re({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),date:i=>new Re({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),class:(i,e)=>new Re({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:i=>new Re({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),audio:i=>new Re({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),file:i=>new Re({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),url:i=>new Re({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),email:i=>new Re({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(i,e)=>new Re({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1,isCached:!1}),object:(i,e)=>new Re({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function Zs(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,Zs(t)])):void 0}}function To(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var D=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ge=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=il(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new D(`Invalid Signature: ${n.message}`,void 0,r)}throw new D(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof i)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new D("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 D("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 D?t:new D(`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 D("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 D("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 D("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 D("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);ut(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new D(`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 D(`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 D?t:new D(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ut(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new D(`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 D(`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 D?t:new D(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new D("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ut(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new D("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ut(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`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,...To(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...To(t)},o=n.parseField(r);ut(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new D(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new D(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...To(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...To(t)},o=n.parseField(r);ut(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new D(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new D(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ut(e,"input")}),this.getOutputFields().forEach(e=>{ut(e,"output")}),this.sigHash=_e("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ll(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof D?e:new D(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ut(e,"input")}),this.getOutputFields().forEach(e=>{ut(e,"output")}),this.validateSignatureConsistency(),this.sigHash=_e("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ll(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof D?e:new D(`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 D(`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 D(`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 D(`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 D("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new D("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return go(e,this.description??"Schema")}};function al(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 ll(i,e,t){let n=i?`"${i}" `:"",r=e.map(al).join(", "),o=t.map(al).join(", ");return`${n}${r} -> ${o}`}function Uc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ut(i,e){if(!i.name||i.name.length===0)throw new D("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Uc(i.name))throw new D(`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(W.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 D(`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 D(`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 D(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Bc(i,e)}function Bc(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new D(`${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 D("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 D("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new D("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new D(`Invalid class option "${o}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new D("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new D("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 D("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&ei(t.fields,i.name,e)}function ei(i,e,t,n=1){for(let[r,o]of Object.entries(i)){let s=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new D(`${o.type} type is not allowed in nested object fields`,s,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&ei(o.fields,s,t,n+1),o.isArray&&o.fields&&ei(o.fields,`${s}[]`,t,n+1)}}var St=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ge(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new gn,this.key={id:this.signature.hash()}}getSignature(){return new ge(this.signature)}setSignature(e){this.signature=new ge(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of o){let c=s[l.name];c!==void 0&&(xo(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return rr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var cl=`
|
|
218
218
|
## Function Call Instructions
|
|
219
219
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
220
220
|
- Output fields should only be generated after all functions have been called.
|
|
@@ -305,7 +305,7 @@ ${m}
|
|
|
305
305
|
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
306
306
|
`))):n.push(t),[{type:"text",text:n.join("")}]}},Co=i=>i.map(e=>`\`${e.title}\``).join(", "),ul=i=>i.map(t=>{let n=t.title,r=t.type?.name?dl(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,s=t.description?` ${fn(t.description)}`:"";return`${n}: (${o})${s}`.trim()}).join(`
|
|
307
307
|
`),pl=i=>i.map(t=>{let n=t.title,r=t.type?.name?dl(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:fn(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${s}`.trim()}).join(`
|
|
308
|
-
`),zc=(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?Ya(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)},dl=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Pt(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 Hc=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function fn(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Kc(i,e){let t=i.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function Wc(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=o.find(c=>"functionId"in c&&c.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function Ro(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Kc(t,n):!1)&&t){let l=Wc(t,n),c=await r({type:"function",results:l});if(c<0||c>=l.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${l.length-1}`);return c}let s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function ml(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await Ro(r,t,i,e)}var wo=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=Vc(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,s=new Map;for(let[a,l]of this.tools.entries())s.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let p=s.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=o.get(u.name)??{};this.setNested(m,d,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new Se(`Missing required arguments for tool '${l.name}': ${p.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[s,a]of Object.entries(r)){let l=[...o,s];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function Vc(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Jc(u);e.push({name:Yc(d),title:Qc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Jc(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Qc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Yc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function fl(i,e,t){let n=new ge(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=ti(o.name),l=hl(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:gl(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=Xc(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let s=ti(o.name),a=hl(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:gl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Xc(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Zc(u),g={name:ti(d),title:eu(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Zc(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function eu(i,e){return`${i} ${e.replace(/\./g," ")}`}function ti(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function gl(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function hl(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var sr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new wo(e)}processSignature(e){let{signature:t}=fl(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var xe=class i extends St{clone=()=>new i(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??Ft)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?ho(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ds()}getMergedCustomLabels(e,t){return Ot(W.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){Ds(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await ml(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),x=a===0,y=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let b,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);b={type:"json_schema",schema:{name:"output",strict:!0,schema:go(I)}}}let v=n?.contextCache?.cacheBreakpoint??"after-examples",k=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,R=n?.contextCache&&(k||v==="after-functions"||v==="after-examples"),C=o?.length&&R?o.map((w,E)=>({...w,cache:E===o.length-1})):o;return await e.chat({chatPrompt:h,functions:C,functionCall:s,modelConfig:f,model:c,responseFormat:b},{sessionId:l,rateLimiter:u,stream:p,debug:A,debugHideSystemPrompt:!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??W.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},p=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,h=n.model,f=this.usage,A=r===0,x=this.isDebug(e,n),y=this.getLogger(e,n),{functions:b,functionCall:I}=za(u,d,A,n),T=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:b,functionCall:I,stepIndex:r});T instanceof ReadableStream?yield*rl({ai:e,model:h,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:b,strictMode:g,span:o,states:a,usage:f,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:x,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*ol({ai:e,model:h,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:b,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:x,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(w=>w.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new pn,d=[...this.functions,...r.functions?ho(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new sr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new sr(d));let h,f,A=this.options?.promptTemplate??Ft;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let x=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,y={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:x};this.promptTemplate=new A(this.signature,y);let b,I=performance.now();Array.isArray(t)?(Vi(t),b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-I,v=this.getMetricsInstruments(),k=this.getMergedCustomLabels(e,r);v&&lo(v,"prompt_render",T,this.getSignatureName(),k);let R=performance.now();p.addRequest(b,r.sessionId);let C=performance.now()-R;v&&lo(v,"memory_update",C,this.getSignatureName(),k);let O=new Map;n.forEach(w=>{O.set(w.index,{})});e:for(let w=0;w<u;w++){let E=c;for(let S=0;S<=E;S++)try{for(let $=0;$<c;$++){n.forEach(P=>{P.content="",P.values={},P.functionCalls=[],P.functionsExecuted=new Set,P.xstate={extractedFields:[],streamedIndex:{},s:-1}}),$>0&&O.forEach((P,V)=>{O.set(V,{})});let M=new Map;n.forEach(P=>{M.set(P.index,{})});try{let P=this.forwardCore({options:r,ai:e,mem:p,stepIndex:w,span:o,traceContext:s,states:n,stopFunctionNames:l}),V=!1;try{for await(let Q of P)if(Q!==void 0){let ne=Q.index,ee=Q.delta,Ie=M.get(ne)??{},me=O.get(ne)??{},Ee={},Xe=!1;for(let Te of Object.keys(ee)){let at=ee[Te],De=Ie[Te],xt;typeof at=="string"&&(typeof De=="string"||De===void 0)?xt=(De??"")+at:Array.isArray(at)&&(Array.isArray(De)||De===void 0)?xt=[...De??[],...at]:xt=at,Ie[Te]=xt;let ye=xt,Ge=me[Te];if(typeof ye=="string"&&typeof Ge=="string")if(ye.startsWith(Ge)){let z=ye.slice(Ge.length);z&&(Ee[Te]=z,Xe=!0,me[Te]=ye)}else Ge.startsWith(ye)||ye!==Ge&&(Ee[Te]=ye,Xe=!0,me[Te]=ye);else if(Array.isArray(ye)&&Array.isArray(Ge)){if(ye.length>Ge.length){let z=ye.slice(Ge.length);Ee[Te]=z,Xe=!0,me[Te]=ye}}else JSON.stringify(ye)!==JSON.stringify(Ge)&&(Ee[Te]=ye,Xe=!0,me[Te]=ye)}Xe&&(yield{version:$,index:Q.index,delta:Ee})}}catch(Q){if(Q instanceof Et)V=!0;else throw Q}if(V?!1:sl(p,l,n,r?.sessionId)){let Q=this.getMetricsInstruments();Q&&ao(Q,w+1,u,this.getSignatureName(),k);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let J=this.getMetricsInstruments();if(J){ao(J,w+1,u,this.getSignatureName(),k);let Q=new Set;n.forEach(ne=>{ne.functionsExecuted.forEach(ee=>Q.add(ee))}),Q.size>0&&Oa(J,!0,Q.size,!0,!1,this.getSignatureName(),k),ka(J,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),k)}return}catch(P){f=P;let V,j=this.isDebug(e,r),J=this.getLogger(e,r),Q=this.getMetricsInstruments(),ne=this.getSignatureName(),ee={error:P,errCount:$,logger:J,metricsInstruments:Q,signatureName:ne,span:o,debug:j,customLabels:k};if(o?.recordException(P),P instanceof Se)V=Ga(ee),h=P;else if(P instanceof ct)V=Ua(ee),h=P;else if(P instanceof de)Ba(ee);else if(!(P instanceof Ke)){let Ie=P,me=Ie instanceof qe&&Ie.status>=500&&Ie.status<600,Ee=Ie instanceof Ne,Xe=Ie instanceof tt;throw me||Ee||Xe?P:ni(P,e,this.signature)}if(V&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(V)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let me of n)me.content="",me.values={},me.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let F=this.getMetricsInstruments();throw F&&Gs(F,c,!1,c,this.getSignatureName(),k),ni(new Error(`Unable to fix validation error: ${(h??f)?.message??(h??f)?.toString()??"unknown error"}
|
|
308
|
+
`),zc=(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?Ya(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)},dl=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Pt(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 Hc=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function fn(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Kc(i,e){let t=i.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function Wc(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=o.find(c=>"functionId"in c&&c.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function Ro(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Kc(t,n):!1)&&t){let l=Wc(t,n),c=await r({type:"function",results:l});if(c<0||c>=l.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${l.length-1}`);return c}let s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function ml(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await Ro(r,t,i,e)}var wo=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=Vc(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,s=new Map;for(let[a,l]of this.tools.entries())s.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let p=s.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=o.get(u.name)??{};this.setNested(m,d,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new Se(`Missing required arguments for tool '${l.name}': ${p.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[s,a]of Object.entries(r)){let l=[...o,s];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function Vc(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Jc(u);e.push({name:Yc(d),title:Qc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Jc(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Qc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Yc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function fl(i,e,t){let n=new ge(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=ti(o.name),l=hl(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:gl(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=Xc(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let s=ti(o.name),a=hl(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:gl(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Xc(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,u]of Object.entries(s)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)o(u.properties,p,u.required||[]);else{let m=Zc(u),g={name:ti(d),title:eu(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Zc(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function eu(i,e){return`${i} ${e.replace(/\./g," ")}`}function ti(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function gl(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function hl(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var sr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new wo(e)}processSignature(e){let{signature:t}=fl(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var xe=class i extends St{clone=()=>new i(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??Ft)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?ho(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Ls()}getMergedCustomLabels(e,t){return Ot(W.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){Ls(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await ml(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),x=a===0,y=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let b,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);b={type:"json_schema",schema:{name:"output",strict:!0,schema:go(I)}}}let v=n?.contextCache?.cacheBreakpoint??"after-examples",k=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,R=n?.contextCache&&(k||v==="after-functions"||v==="after-examples"),C=o?.length&&R?o.map((w,E)=>({...w,cache:E===o.length-1})):o;return await e.chat({chatPrompt:h,functions:C,functionCall:s,modelConfig:f,model:c,responseFormat:b},{sessionId:l,rateLimiter:u,stream:p,debug:A,debugHideSystemPrompt:!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??W.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},p=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,h=n.model,f=this.usage,A=r===0,x=this.isDebug(e,n),y=this.getLogger(e,n),{functions:b,functionCall:I}=za(u,d,A,n),T=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:b,functionCall:I,stepIndex:r});T instanceof ReadableStream?yield*rl({ai:e,model:h,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:b,strictMode:g,span:o,states:a,usage:f,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:x,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*ol({ai:e,model:h,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:b,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:x,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(w=>w.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new pn,d=[...this.functions,...r.functions?ho(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new sr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new sr(d));let h,f,A=this.options?.promptTemplate??Ft;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let x=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,y={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:x};this.promptTemplate=new A(this.signature,y);let b,I=performance.now();Array.isArray(t)?(Vi(t),b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-I,v=this.getMetricsInstruments(),k=this.getMergedCustomLabels(e,r);v&&lo(v,"prompt_render",T,this.getSignatureName(),k);let R=performance.now();p.addRequest(b,r.sessionId);let C=performance.now()-R;v&&lo(v,"memory_update",C,this.getSignatureName(),k);let O=new Map;n.forEach(w=>{O.set(w.index,{})});e:for(let w=0;w<u;w++){let E=c;for(let S=0;S<=E;S++)try{for(let $=0;$<c;$++){n.forEach(P=>{P.content="",P.values={},P.functionCalls=[],P.functionsExecuted=new Set,P.xstate={extractedFields:[],streamedIndex:{},s:-1}}),$>0&&O.forEach((P,V)=>{O.set(V,{})});let M=new Map;n.forEach(P=>{M.set(P.index,{})});try{let P=this.forwardCore({options:r,ai:e,mem:p,stepIndex:w,span:o,traceContext:s,states:n,stopFunctionNames:l}),V=!1;try{for await(let Q of P)if(Q!==void 0){let ne=Q.index,ee=Q.delta,Ie=M.get(ne)??{},me=O.get(ne)??{},Ee={},Xe=!1;for(let Te of Object.keys(ee)){let at=ee[Te],Le=Ie[Te],xt;typeof at=="string"&&(typeof Le=="string"||Le===void 0)?xt=(Le??"")+at:Array.isArray(at)&&(Array.isArray(Le)||Le===void 0)?xt=[...Le??[],...at]:xt=at,Ie[Te]=xt;let ye=xt,Ge=me[Te];if(typeof ye=="string"&&typeof Ge=="string")if(ye.startsWith(Ge)){let z=ye.slice(Ge.length);z&&(Ee[Te]=z,Xe=!0,me[Te]=ye)}else Ge.startsWith(ye)||ye!==Ge&&(Ee[Te]=ye,Xe=!0,me[Te]=ye);else if(Array.isArray(ye)&&Array.isArray(Ge)){if(ye.length>Ge.length){let z=ye.slice(Ge.length);Ee[Te]=z,Xe=!0,me[Te]=ye}}else JSON.stringify(ye)!==JSON.stringify(Ge)&&(Ee[Te]=ye,Xe=!0,me[Te]=ye)}Xe&&(yield{version:$,index:Q.index,delta:Ee})}}catch(Q){if(Q instanceof Et)V=!0;else throw Q}if(V?!1:sl(p,l,n,r?.sessionId)){let Q=this.getMetricsInstruments();Q&&ao(Q,w+1,u,this.getSignatureName(),k);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let J=this.getMetricsInstruments();if(J){ao(J,w+1,u,this.getSignatureName(),k);let Q=new Set;n.forEach(ne=>{ne.functionsExecuted.forEach(ee=>Q.add(ee))}),Q.size>0&&Oa(J,!0,Q.size,!0,!1,this.getSignatureName(),k),ka(J,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),k)}return}catch(P){f=P;let V,j=this.isDebug(e,r),J=this.getLogger(e,r),Q=this.getMetricsInstruments(),ne=this.getSignatureName(),ee={error:P,errCount:$,logger:J,metricsInstruments:Q,signatureName:ne,span:o,debug:j,customLabels:k};if(o?.recordException(P),P instanceof Se)V=Ga(ee),h=P;else if(P instanceof ct)V=Ua(ee),h=P;else if(P instanceof de)Ba(ee);else if(!(P instanceof Ke)){let Ie=P,me=Ie instanceof qe&&Ie.status>=500&&Ie.status<600,Ee=Ie instanceof Ne,Xe=Ie instanceof tt;throw me||Ee||Xe?P:ni(P,e,this.signature)}if(V&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(V)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let me of n)me.content="",me.values={},me.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let F=this.getMetricsInstruments();throw F&&Gs(F,c,!1,c,this.getSignatureName(),k),ni(new Error(`Unable to fix validation error: ${(h??f)?.message??(h??f)?.toString()??"unknown error"}
|
|
309
309
|
|
|
310
310
|
LLM Output:
|
|
311
311
|
${n.map($=>$.content).join(`
|
|
@@ -442,7 +442,7 @@ Score: ${t.value.score.toFixed(3)}
|
|
|
442
442
|
Config: ${JSON.stringify(t.value.config)}
|
|
443
443
|
${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
|
|
444
444
|
${JSON.stringify(t)}
|
|
445
|
-
${e}`}i(n)}},ar=ri();var oi={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Fo,du=i=>{if(Fo)return Fo;if(i)return Fo=mu(i),Fo};var _o=oi,Rl=i=>{_o={..._o,...i}},wl=()=>({..._o}),mu=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"})}),it=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=_o.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},gu=(i,e,t,n,r,o)=>{try{let s=it({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,s),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,s),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record optimization metric:",s)}},hu=(i,e,t,n,r,o,s)=>{try{let a=it({optimizer_type:o,...s});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},fu=(i,e,t,n)=>{try{let r=it({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},xu=(i,e,t,n,r,o)=>{try{let s=it({optimizer_type:n,...o});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,s),i.costUsageCounter&&i.costUsageCounter.add(t,s),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,s)}catch(s){console.warn("Failed to record resource usage metric:",s)}},Au=(i,e,t,n)=>{try{let r=it({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},yu=(i,e,t,n,r)=>{try{let o=it({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,o),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,o),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},bu=(i,e,t,n,r,o)=>{try{let s=it({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,s),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,s)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,s),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,s))}catch(s){console.warn("Failed to record checkpoint metric:",s)}},Iu=(i,e,t,n,r,o)=>{try{let s=it({optimizer_type:n,...o});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,s),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,s),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,s),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,s)}catch(s){console.warn("Failed to record Pareto metric:",s)}},Tu=(i,e,t,n,r,o,s)=>{try{let a=it({optimizer_type:o,...s});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Cu=(i,e,t,n,r)=>{try{let o=it({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Ru=(i,e,t,n,r)=>{try{let o=it({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,o),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,o),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},pt=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)}},lr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},Le=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 lr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=du(W.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?ar:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return Ot(W.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a,r);let l,c=(g,h,f,A,x,y,b,I={},T)=>{this.getOptimizerLogger(T)?.({name:"RoundProgress",value:{round:g,totalRounds:T?.maxIterations??0,currentScore:h,bestScore:y,configuration:f}}),this.updateOptimizationProgress(g,h,f,A,x,y,b,I,T)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:u}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,s,a,r),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),p=this.calculateHypervolume(u);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);let d=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:u,hypervolume:p,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let p=0;p<u.length;p++){let d=u[p],m=async({prediction:g,example:h})=>{let f=await n({prediction:g,example:h}),A=0;for(let[x,y]of Object.entries(f))A+=y*(d[x]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[u]||0,f=0;for(let[A,x]of Object.entries(g))A!==u&&x<.3&&(f+=(.3-x)*2);return h-f};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let s of e)o[s]=s===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new xe(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let d of u)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[h,f]of Object.entries(g))c[h]||(c[h]=[]),c[h].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,s=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,p=c.scores[o]||0;s+=u*(p-l),l=Math.max(l,p)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let p={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};u=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,c,e,s)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown",t)}return s}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,s=(t.match(/output:/g)||[]).length;Tu(this.metricsInstruments,o,s,0,0,e,r)}Ru(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);gu(this.metricsInstruments,e,t,n,r,s),Au(this.metricsInstruments,e,n,s);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;xu(this.metricsInstruments,l,a,n,void 0,s)}recordConvergenceMetrics(e,t,n,r,o,s){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(s);hu(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);fu(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);yu(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);bu(this.metricsInstruments,e,t,n,r,s)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);Iu(this.metricsInstruments,e,t,n,r,s)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Cu(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??W.optimizerLogger??ar}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let u=t.bootstrappedDemos;typeof u=="number"&&u===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let s=this.getOptimizerLogger(r);s&&s(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function Sl(i){return ge.create(i)}function Me(i,e){let t=typeof i=="string"?ge.create(i):i;return new xe(t,e)}function vl(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function dt(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(vl(i[s].scores,i[n].scores,e)){o=!0;break}vl(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Ye(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-s,0);o+=l*u,s=Math.max(s,c)}return o}function Nt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function No(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function cr(i,e){let t=new Set;for(let u of i)for(let p of u)t.add(p);let r=[...Array.from(t)].sort((u,p)=>(e[u]??0)-(e[p]??0)),o=new Set,s=(u,p)=>{for(let d of i){if(!d.has(u))continue;let m=!1;for(let g of p)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(o.has(u))continue;let p=new Set(r.filter(d=>d!==u&&!o.has(d)));if(s(u,p)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function ur(i,e,t){let n=cr(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let p=0;p<c;p++)o.push(u)}if(o.length===0)return 0;let s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var bn=class i extends Le{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(M,P)=>{try{e.setInstruction?.(M);let V=await e.forward(this.studentAI,P,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:V,example:P})||{}}catch{return{}}},p=async(M,P)=>{let V=[];for(let j of P)V.push(await u(M,j));return No(V)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=M=>{let P=r?.paretoMetricKey,V=r?.paretoScalarize;if(typeof V=="function")return V(M);if(P)return Number.isFinite(M[P])?M[P]:0;let j=Object.values(M);return j.length?j.reduce((J,Q)=>J+Q,0)/j.length:0},h=[],f=async(M,P)=>{let V=[];for(let j of P){let J=await u(M,j);V.push(g(J))}return V};h.push(await f(d,l));let A=()=>{let M=h[0]?.length??0,P=[];for(let j=0;j<M;j++){let J=Number.NEGATIVE_INFINITY,Q=new Set;for(let ne=0;ne<h.length;ne++){let ee=h[ne][j];ee>J+this.tieEpsilon?(J=ee,Q.clear(),Q.add(ne)):Math.abs(ee-J)<=this.tieEpsilon&&Q.add(ne)}P.push(Q)}let V=h.map(j=>Nt(j));return ur(P,V)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(x),b=this.getOptimizerLogger(r),I=r?.verbose??this.verbose?M=>console.log(`[GEPA] ${M}`):M=>{};b?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),I(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${y}`);let T=0,v=dt(m.map((M,P)=>({idx:P,scores:M.scores})),this.tieEpsilon).map(M=>M.idx),k;for(let M=0;M<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));M++){let P=h[0]?.length??0,V=[];for(let G=0;G<P;G++){let U=Number.NEGATIVE_INFINITY,Y=new Set;for(let te=0;te<h.length;te++){let N=h[te][G];N>U+this.tieEpsilon?(U=N,Y.clear(),Y.add(te)):Math.abs(N-U)<=this.tieEpsilon&&Y.add(te)}V.push(Y)}let j=h.map(G=>Nt(G));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let G=_=>{let B=[],X=_;for(;X!==void 0;)B.push(X),X=m[X]?.parent;return B},U=_=>_.length?_[Math.floor(this.rand()*_.length)]:void 0,Y=cr(V,j),te=new Set;for(let _ of Y)for(let B of _)te.add(B);let N=Array.from(te),D;for(let _=0;_<10&&!D&&!(N.length<2);_++){let B=U(N),X=U(N);if(B===X)continue;X<B&&([B,X]=[X,B]);let pe=new Set(G(B)),Z=new Set(G(X));if(pe.has(X)||Z.has(B))continue;let re=[...pe].filter(we=>Z.has(we));if(re.length===0)continue;let se=re.map(we=>Math.max(1e-9,j[we])),ce=this.rand()*se.reduce((we,ze)=>we+ze,0),be=re[re.length-1];for(let we=0;we<re.length;we++){if(ce<se[we]){be=re[we];break}ce-=se[we]}D={i:B,j:X,a:be}}if(this.lastIterFoundNewProgram=!1,D){let{i:_,j:B,a:X}=D,pe=j[X],Z=j[_],re=j[B],se=m[X].instruction,ce=m[_].instruction,be=m[B].instruction,we=ce===se&&be!==ce||be===se&&ce!==be,ze=pe<=Math.min(Z,re)&&we,Pe="",Ue="i",ue=!1;if(ze){let mt=`${_}|${B}|${X}`;if(this.mergeAttemptKeys.has(mt))ze=!1;else{ce===se&&be!==ce?(Pe=be,Ue="j"):be===se&&ce!==be?(Pe=ce,Ue="i"):ce!==se&&be!==se&&ce!==be?Z>re||Z===re&&this.rand()<.5?(Pe=ce,Ue="i"):(Pe=be,Ue="j"):(Pe=ce,Ue="i");let At=`${Math.min(_,B)}|${Math.max(_,B)}|${Ue}`;if(this.mergeCompositionKeys.has(At))ze=!1;else{this.mergeAttemptKeys.add(mt),this.mergeCompositionKeys.add(At);let Ze=h[_],yt=h[B],bt=Array.from({length:Ze.length},(ae,Fe)=>Fe),gt=bt.filter(ae=>(Ze[ae]??0)>(yt[ae]??0)),It=bt.filter(ae=>(yt[ae]??0)>(Ze[ae]??0)),vt=bt.filter(ae=>!(gt.includes(ae)||It.includes(ae))),H=5,he=Math.ceil(H/3),lt=(ae,Fe)=>{if(Fe<=0||ae.length===0)return[];if(ae.length<=Fe)return[...ae];let En=[],Ar=new Set;for(;En.length<Fe;){let et=Math.floor(this.rand()*ae.length);Ar.has(et)||(Ar.add(et),En.push(ae[et]))}return En},Be=[];Be.push(...lt(gt,Math.min(he,gt.length))),Be.push(...lt(It,Math.min(he,It.length)));let je=H-Be.length;Be.push(...lt(vt,Math.max(0,je)));let xr=H-Be.length;if(xr>0){let ae=bt.filter(Fe=>!Be.includes(Fe));Be.push(...lt(ae,Math.min(xr,ae.length)))}let Qo=Be.slice(0,Math.min(H,bt.length)),Kl=Qo.map(ae=>l[ae]);ue=!0;let Wl=(await f(Pe,Kl)).reduce((ae,Fe)=>ae+Fe,0),Vl=Qo.reduce((ae,Fe)=>ae+(Ze[Fe]??0),0),Jl=Qo.reduce((ae,Fe)=>ae+(yt[Fe]??0),0);if(Wl>=Math.max(Vl,Jl)+this.tieEpsilon){I(`Iteration ${M+1}: Merge accepted (programs ${_} + ${B} via ancestor ${X})`);let ae=await p(Pe,l);m.push({instruction:Pe,parent:X,scores:ae}),h.push(await f(Pe,l));let Fe=v.length,En=Ye(v.map(et=>m[et].scores))??0;v=dt(m.map((et,Ql)=>({idx:Ql,scores:et.scores})),this.tieEpsilon).map(et=>et.idx);let Ar=Ye(v.map(et=>m[et].scores))??0;(v.length>Fe||Ar>En+1e-6)&&(T=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ue)continue}}let J=ur(V,j,()=>this.rand()),Q=this.minibatch?this.nextMinibatchIndices(c.length,M).map(G=>c[G]):c;if(r?.skipPerfectScore??!0){let G=Number(r?.perfectScore??1),U=await f(m[J].instruction,Q);if(U.length>0&&U.every(Y=>Y>=G))continue}let ne=!1,ee=m[J].instruction,Ie="reflective_mutation",me,Ee;if(ne){let G=(J+1)%m.length;ee=await this.mergeInstructions(m[J].instruction,m[G].instruction,r),Ie="merge",this.mergesUsed+=1}else{let G=r?.gepaAdapter;if(G){try{let U={instruction:m[J].instruction},Y=await G.evaluate(Q,U,!0);me=Array.isArray(Y?.scores)?Y.scores.reduce((_,B)=>_+(Number(B)||0),0):void 0;let te=G.make_reflective_dataset(U,Y,["instruction"]),N=await G.propose_new_texts?.(U,te,["instruction"]),D=N?.instruction??(N?Object.values(N)[0]:void 0);typeof D=="string"&&D.length>0?ee=D:ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:_,example:B})=>{let X=await n({prediction:_,example:B}),pe=Object.values(X||{});return pe.length?pe.reduce((Z,re)=>Z+re,0)/pe.length:0},r)}catch{ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((D,_)=>D+_,0)/N.length:0},r)}if(me!==void 0)try{let U=await G.evaluate(Q,{instruction:ee},!1);Ee=Array.isArray(U?.scores)?U.scores.reduce((Y,te)=>Y+(Number(te)||0),0):void 0}catch{}}else ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((D,_)=>D+_,0)/N.length:0},r)}let Xe=await f(m[J].instruction,Q),Te=await f(ee,Q),at=Xe.reduce((G,U)=>G+U,0),De=Te.reduce((G,U)=>G+U,0);if(this.currentRound=M+1,await this.updateOptimizationProgress(this.currentRound,De,{instructionLen:ee.length,parent:J,totalRounds:this.numTrials},"GEPA",{strategy:Ie,paretoSetSize:l.length},De,{instructionLen:m[J].instruction.length,idx:J},{...r??{},maxIterations:this.numTrials}),!(De>at+this.tieEpsilon&&(me===void 0||Ee===void 0||Ee>me+this.tieEpsilon))){if(I(`Iteration ${M+1}: Rejected (child=${De.toFixed(3)} <= parent=${at.toFixed(3)})`),++T>=this.earlyStoppingTrials){I(`Early stopping: ${T} iterations without improvement`);break}continue}I(`Iteration ${M+1}: Accepted (child=${De.toFixed(3)} > parent=${at.toFixed(3)})`);let ye=await p(ee,l);m.push({instruction:ee,parent:J,scores:ye}),h.push(await f(ee,l));let Ge=v.length,z=Ye(v.map(G=>m[G].scores))??0;v=dt(m.map((G,U)=>({idx:U,scores:G.scores})),this.tieEpsilon).map(G=>G.idx);let ie=Ye(v.map(G=>m[G].scores))??0;if(v.length>Ge||ie>z+1e-6)T=0,I(`Iteration ${M+1}: Archive improved (size=${v.length}, hv=${ie.toFixed(4)})`);else if(T++,I(`Iteration ${M+1}: Archive unchanged (stagnation=${T}/${this.earlyStoppingTrials})`),T>=this.earlyStoppingTrials){I(`Early stopping: ${T} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=dt(m.map((M,P)=>({idx:P,scores:M.scores})),this.tieEpsilon),C=R.length>0?Math.max(...R.map(M=>g(M.scores))):0,O;if(R.length>0){let M=Number.NEGATIVE_INFINITY;for(let P of R){let V=g(P.scores);V>M&&(M=V,O=P.idx)}}let w=Ye(R.map(M=>M.scores));this.stats.convergenceInfo.converged=!0;let E=this.getMergedCustomLabels(r);this.recordParetoMetrics(R.length,m.length,"GEPA",w,E);let S=Date.now()-o,F=typeof O=="number"?new pt({bestScore:C,stats:this.stats,instruction:m[O].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:S,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,$=this.generateOptimizationReport(R,w,C);return{demos:[],stats:this.stats,bestScore:C,paretoFront:R.map(M=>({demos:[],scores:M.scores,configuration:{candidate:M.idx,instruction:m[M.idx].instruction},dominatedSolutions:M.dominated})),paretoFrontSize:R.length,hypervolume:w,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:F,report:$}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Nt(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,s){let a=s??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let h=await r({prediction:g,example:m});a.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,c=o?.feedbackFn,u=()=>{let m=[];for(let g=0;g<a.length;g++){let h=a[g],f=`# Example ${g+1}
|
|
445
|
+
${e}`}i(n)}},ar=ri();var oi={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Fo,du=i=>{if(Fo)return Fo;if(i)return Fo=mu(i),Fo};var _o=oi,Rl=i=>{_o={..._o,...i}},wl=()=>({..._o}),mu=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"})}),it=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=_o.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},gu=(i,e,t,n,r,o)=>{try{let s=it({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,s),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,s),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record optimization metric:",s)}},hu=(i,e,t,n,r,o,s)=>{try{let a=it({optimizer_type:o,...s});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},fu=(i,e,t,n)=>{try{let r=it({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},xu=(i,e,t,n,r,o)=>{try{let s=it({optimizer_type:n,...o});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,s),i.costUsageCounter&&i.costUsageCounter.add(t,s),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,s)}catch(s){console.warn("Failed to record resource usage metric:",s)}},Au=(i,e,t,n)=>{try{let r=it({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},yu=(i,e,t,n,r)=>{try{let o=it({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,o),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,o),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},bu=(i,e,t,n,r,o)=>{try{let s=it({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,s),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,s)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,s),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,s))}catch(s){console.warn("Failed to record checkpoint metric:",s)}},Iu=(i,e,t,n,r,o)=>{try{let s=it({optimizer_type:n,...o});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,s),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,s),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,s),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,s)}catch(s){console.warn("Failed to record Pareto metric:",s)}},Tu=(i,e,t,n,r,o,s)=>{try{let a=it({optimizer_type:o,...s});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Cu=(i,e,t,n,r)=>{try{let o=it({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Ru=(i,e,t,n,r)=>{try{let o=it({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,o),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,o),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},pt=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)}},lr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},De=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 lr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=du(W.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?ar:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return Ot(W.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a,r);let l,c=(g,h,f,A,x,y,b,I={},T)=>{this.getOptimizerLogger(T)?.({name:"RoundProgress",value:{round:g,totalRounds:T?.maxIterations??0,currentScore:h,bestScore:y,configuration:f}}),this.updateOptimizationProgress(g,h,f,A,x,y,b,I,T)},u=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:u}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,s,a,r),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),p=this.calculateHypervolume(u);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);let d=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:u,hypervolume:p,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let p=0;p<u.length;p++){let d=u[p],m=async({prediction:g,example:h})=>{let f=await n({prediction:g,example:h}),A=0;for(let[x,y]of Object.entries(f))A+=y*(d[x]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[u]||0,f=0;for(let[A,x]of Object.entries(g))A!==u&&x<.3&&(f+=(.3-x)*2);return h-f};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let s of e)o[s]=s===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new xe(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let d of u)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[h,f]of Object.entries(g))c[h]||(c[h]=[]),c[h].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,s=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,p=c.scores[o]||0;s+=u*(p-l),l=Math.max(l,p)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let p={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};u=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,c,e,s)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown",t)}return s}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,s=(t.match(/output:/g)||[]).length;Tu(this.metricsInstruments,o,s,0,0,e,r)}Ru(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);gu(this.metricsInstruments,e,t,n,r,s),Au(this.metricsInstruments,e,n,s);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;xu(this.metricsInstruments,l,a,n,void 0,s)}recordConvergenceMetrics(e,t,n,r,o,s){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(s);hu(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);fu(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);yu(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);bu(this.metricsInstruments,e,t,n,r,s)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(o);Iu(this.metricsInstruments,e,t,n,r,s)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Cu(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??W.optimizerLogger??ar}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let u=t.bootstrappedDemos;typeof u=="number"&&u===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let s=this.getOptimizerLogger(r);s&&s(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function Sl(i){return ge.create(i)}function Me(i,e){let t=typeof i=="string"?ge.create(i):i;return new xe(t,e)}function vl(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function dt(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(vl(i[s].scores,i[n].scores,e)){o=!0;break}vl(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Ye(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-s,0);o+=l*u,s=Math.max(s,c)}return o}function Nt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function No(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function cr(i,e){let t=new Set;for(let u of i)for(let p of u)t.add(p);let r=[...Array.from(t)].sort((u,p)=>(e[u]??0)-(e[p]??0)),o=new Set,s=(u,p)=>{for(let d of i){if(!d.has(u))continue;let m=!1;for(let g of p)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(o.has(u))continue;let p=new Set(r.filter(d=>d!==u&&!o.has(d)));if(s(u,p)){o.add(u),a=!0;break}}}let l=r.filter(u=>!o.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function ur(i,e,t){let n=cr(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let p=0;p<c;p++)o.push(u)}if(o.length===0)return 0;let s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var bn=class i extends De{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(M,P)=>{try{e.setInstruction?.(M);let V=await e.forward(this.studentAI,P,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:V,example:P})||{}}catch{return{}}},p=async(M,P)=>{let V=[];for(let j of P)V.push(await u(M,j));return No(V)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=M=>{let P=r?.paretoMetricKey,V=r?.paretoScalarize;if(typeof V=="function")return V(M);if(P)return Number.isFinite(M[P])?M[P]:0;let j=Object.values(M);return j.length?j.reduce((J,Q)=>J+Q,0)/j.length:0},h=[],f=async(M,P)=>{let V=[];for(let j of P){let J=await u(M,j);V.push(g(J))}return V};h.push(await f(d,l));let A=()=>{let M=h[0]?.length??0,P=[];for(let j=0;j<M;j++){let J=Number.NEGATIVE_INFINITY,Q=new Set;for(let ne=0;ne<h.length;ne++){let ee=h[ne][j];ee>J+this.tieEpsilon?(J=ee,Q.clear(),Q.add(ne)):Math.abs(ee-J)<=this.tieEpsilon&&Q.add(ne)}P.push(Q)}let V=h.map(j=>Nt(j));return ur(P,V)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(x),b=this.getOptimizerLogger(r),I=r?.verbose??this.verbose?M=>console.log(`[GEPA] ${M}`):M=>{};b?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),I(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${y}`);let T=0,v=dt(m.map((M,P)=>({idx:P,scores:M.scores})),this.tieEpsilon).map(M=>M.idx),k;for(let M=0;M<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));M++){let P=h[0]?.length??0,V=[];for(let G=0;G<P;G++){let U=Number.NEGATIVE_INFINITY,Y=new Set;for(let te=0;te<h.length;te++){let N=h[te][G];N>U+this.tieEpsilon?(U=N,Y.clear(),Y.add(te)):Math.abs(N-U)<=this.tieEpsilon&&Y.add(te)}V.push(Y)}let j=h.map(G=>Nt(G));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let G=_=>{let B=[],X=_;for(;X!==void 0;)B.push(X),X=m[X]?.parent;return B},U=_=>_.length?_[Math.floor(this.rand()*_.length)]:void 0,Y=cr(V,j),te=new Set;for(let _ of Y)for(let B of _)te.add(B);let N=Array.from(te),L;for(let _=0;_<10&&!L&&!(N.length<2);_++){let B=U(N),X=U(N);if(B===X)continue;X<B&&([B,X]=[X,B]);let pe=new Set(G(B)),Z=new Set(G(X));if(pe.has(X)||Z.has(B))continue;let re=[...pe].filter(we=>Z.has(we));if(re.length===0)continue;let se=re.map(we=>Math.max(1e-9,j[we])),ce=this.rand()*se.reduce((we,ze)=>we+ze,0),be=re[re.length-1];for(let we=0;we<re.length;we++){if(ce<se[we]){be=re[we];break}ce-=se[we]}L={i:B,j:X,a:be}}if(this.lastIterFoundNewProgram=!1,L){let{i:_,j:B,a:X}=L,pe=j[X],Z=j[_],re=j[B],se=m[X].instruction,ce=m[_].instruction,be=m[B].instruction,we=ce===se&&be!==ce||be===se&&ce!==be,ze=pe<=Math.min(Z,re)&&we,Pe="",Ue="i",ue=!1;if(ze){let mt=`${_}|${B}|${X}`;if(this.mergeAttemptKeys.has(mt))ze=!1;else{ce===se&&be!==ce?(Pe=be,Ue="j"):be===se&&ce!==be?(Pe=ce,Ue="i"):ce!==se&&be!==se&&ce!==be?Z>re||Z===re&&this.rand()<.5?(Pe=ce,Ue="i"):(Pe=be,Ue="j"):(Pe=ce,Ue="i");let At=`${Math.min(_,B)}|${Math.max(_,B)}|${Ue}`;if(this.mergeCompositionKeys.has(At))ze=!1;else{this.mergeAttemptKeys.add(mt),this.mergeCompositionKeys.add(At);let Ze=h[_],yt=h[B],bt=Array.from({length:Ze.length},(ae,Fe)=>Fe),gt=bt.filter(ae=>(Ze[ae]??0)>(yt[ae]??0)),It=bt.filter(ae=>(yt[ae]??0)>(Ze[ae]??0)),vt=bt.filter(ae=>!(gt.includes(ae)||It.includes(ae))),H=5,he=Math.ceil(H/3),lt=(ae,Fe)=>{if(Fe<=0||ae.length===0)return[];if(ae.length<=Fe)return[...ae];let En=[],Ar=new Set;for(;En.length<Fe;){let et=Math.floor(this.rand()*ae.length);Ar.has(et)||(Ar.add(et),En.push(ae[et]))}return En},Be=[];Be.push(...lt(gt,Math.min(he,gt.length))),Be.push(...lt(It,Math.min(he,It.length)));let je=H-Be.length;Be.push(...lt(vt,Math.max(0,je)));let xr=H-Be.length;if(xr>0){let ae=bt.filter(Fe=>!Be.includes(Fe));Be.push(...lt(ae,Math.min(xr,ae.length)))}let Qo=Be.slice(0,Math.min(H,bt.length)),Kl=Qo.map(ae=>l[ae]);ue=!0;let Wl=(await f(Pe,Kl)).reduce((ae,Fe)=>ae+Fe,0),Vl=Qo.reduce((ae,Fe)=>ae+(Ze[Fe]??0),0),Jl=Qo.reduce((ae,Fe)=>ae+(yt[Fe]??0),0);if(Wl>=Math.max(Vl,Jl)+this.tieEpsilon){I(`Iteration ${M+1}: Merge accepted (programs ${_} + ${B} via ancestor ${X})`);let ae=await p(Pe,l);m.push({instruction:Pe,parent:X,scores:ae}),h.push(await f(Pe,l));let Fe=v.length,En=Ye(v.map(et=>m[et].scores))??0;v=dt(m.map((et,Ql)=>({idx:Ql,scores:et.scores})),this.tieEpsilon).map(et=>et.idx);let Ar=Ye(v.map(et=>m[et].scores))??0;(v.length>Fe||Ar>En+1e-6)&&(T=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ue)continue}}let J=ur(V,j,()=>this.rand()),Q=this.minibatch?this.nextMinibatchIndices(c.length,M).map(G=>c[G]):c;if(r?.skipPerfectScore??!0){let G=Number(r?.perfectScore??1),U=await f(m[J].instruction,Q);if(U.length>0&&U.every(Y=>Y>=G))continue}let ne=!1,ee=m[J].instruction,Ie="reflective_mutation",me,Ee;if(ne){let G=(J+1)%m.length;ee=await this.mergeInstructions(m[J].instruction,m[G].instruction,r),Ie="merge",this.mergesUsed+=1}else{let G=r?.gepaAdapter;if(G){try{let U={instruction:m[J].instruction},Y=await G.evaluate(Q,U,!0);me=Array.isArray(Y?.scores)?Y.scores.reduce((_,B)=>_+(Number(B)||0),0):void 0;let te=G.make_reflective_dataset(U,Y,["instruction"]),N=await G.propose_new_texts?.(U,te,["instruction"]),L=N?.instruction??(N?Object.values(N)[0]:void 0);typeof L=="string"&&L.length>0?ee=L:ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:_,example:B})=>{let X=await n({prediction:_,example:B}),pe=Object.values(X||{});return pe.length?pe.reduce((Z,re)=>Z+re,0)/pe.length:0},r)}catch{ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((L,_)=>L+_,0)/N.length:0},r)}if(me!==void 0)try{let U=await G.evaluate(Q,{instruction:ee},!1);Ee=Array.isArray(U?.scores)?U.scores.reduce((Y,te)=>Y+(Number(te)||0),0):void 0}catch{}}else ee=await this.reflectInstruction(m[J].instruction,e,Q,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((L,_)=>L+_,0)/N.length:0},r)}let Xe=await f(m[J].instruction,Q),Te=await f(ee,Q),at=Xe.reduce((G,U)=>G+U,0),Le=Te.reduce((G,U)=>G+U,0);if(this.currentRound=M+1,await this.updateOptimizationProgress(this.currentRound,Le,{instructionLen:ee.length,parent:J,totalRounds:this.numTrials},"GEPA",{strategy:Ie,paretoSetSize:l.length},Le,{instructionLen:m[J].instruction.length,idx:J},{...r??{},maxIterations:this.numTrials}),!(Le>at+this.tieEpsilon&&(me===void 0||Ee===void 0||Ee>me+this.tieEpsilon))){if(I(`Iteration ${M+1}: Rejected (child=${Le.toFixed(3)} <= parent=${at.toFixed(3)})`),++T>=this.earlyStoppingTrials){I(`Early stopping: ${T} iterations without improvement`);break}continue}I(`Iteration ${M+1}: Accepted (child=${Le.toFixed(3)} > parent=${at.toFixed(3)})`);let ye=await p(ee,l);m.push({instruction:ee,parent:J,scores:ye}),h.push(await f(ee,l));let Ge=v.length,z=Ye(v.map(G=>m[G].scores))??0;v=dt(m.map((G,U)=>({idx:U,scores:G.scores})),this.tieEpsilon).map(G=>G.idx);let ie=Ye(v.map(G=>m[G].scores))??0;if(v.length>Ge||ie>z+1e-6)T=0,I(`Iteration ${M+1}: Archive improved (size=${v.length}, hv=${ie.toFixed(4)})`);else if(T++,I(`Iteration ${M+1}: Archive unchanged (stagnation=${T}/${this.earlyStoppingTrials})`),T>=this.earlyStoppingTrials){I(`Early stopping: ${T} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=dt(m.map((M,P)=>({idx:P,scores:M.scores})),this.tieEpsilon),C=R.length>0?Math.max(...R.map(M=>g(M.scores))):0,O;if(R.length>0){let M=Number.NEGATIVE_INFINITY;for(let P of R){let V=g(P.scores);V>M&&(M=V,O=P.idx)}}let w=Ye(R.map(M=>M.scores));this.stats.convergenceInfo.converged=!0;let E=this.getMergedCustomLabels(r);this.recordParetoMetrics(R.length,m.length,"GEPA",w,E);let S=Date.now()-o,F=typeof O=="number"?new pt({bestScore:C,stats:this.stats,instruction:m[O].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:S,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,$=this.generateOptimizationReport(R,w,C);return{demos:[],stats:this.stats,bestScore:C,paretoFront:R.map(M=>({demos:[],scores:M.scores,configuration:{candidate:M.idx,instruction:m[M.idx].instruction},dominatedSolutions:M.dominated})),paretoFrontSize:R.length,hypervolume:w,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:F,report:$}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Nt(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,s){let a=s??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let h=await r({prediction:g,example:m});a.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,c=o?.feedbackFn,u=()=>{let m=[];for(let g=0;g<a.length;g++){let h=a[g],f=`# Example ${g+1}
|
|
446
446
|
`;if(f+=`## Inputs
|
|
447
447
|
`,typeof h.input=="object"&&h.input!==null)for(let[x,y]of Object.entries(h.input))f+=`### ${x}
|
|
448
448
|
${String(y).trim()}
|
|
@@ -494,7 +494,7 @@ ${n.map(s=>`- ${s}`).join(`
|
|
|
494
494
|
`)}
|
|
495
495
|
|
|
496
496
|
Output ONLY the JSON array, no explanation.
|
|
497
|
-
`.trim(),o=new xe("count:number -> examples:json");o.setInstruction(r);try{let s=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(s.examples)?s.examples.slice(0,e):[]}catch(s){return console.warn("AxSynth: Edge case generation failed:",s),[]}}async labelInput(e){return await new xe(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var $o=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new yn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,s=[...n.examples??[]];if(n.useTraces!==!1){let T=(await this.getTraces()).filter(v=>v.input&&v.output).map(v=>({...v.input,...v.output}));s=[...s,...T]}if(n.generateExamples||s.length===0){let I=n.synthCount??20,T={teacher:r,...n.synthOptions},R=(await new In(this.gen.getSignature(),T).generate(I)).examples.map(C=>({...C.input,...C.expected}));s=[...s,...R]}if(s.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...s].sort(()=>Math.random()-.5),c=Math.floor(l.length*(1-a)),u=l.slice(0,c),p=l.slice(c),d=n.metric;if(!d){let I={ai:r,criteria:n.criteria,...n.judgeOptions};d=new An(this.gen.getSignature(),I).toMetricFn()}let m=new bn({studentAI:r,numTrials:o,minibatch:!0,minibatchSize:10}),g=o*Math.max(u.length,10),h=await m.compile(this.gen,u,d,{validationExamples:p,maxMetricCalls:g});if(!h.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");h.optimizedProgram.instruction&&this.gen.setInstruction(h.optimizedProgram.instruction),this.currentScore=h.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,A=f,y=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,b={type:"checkpoint",name:this.options.name,version:y,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:o,trainingExamples:u.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,b),{score:f,improvement:A,checkpointVersion:y,stats:{trainingExamples:u.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var
|
|
497
|
+
`.trim(),o=new xe("count:number -> examples:json");o.setInstruction(r);try{let s=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(s.examples)?s.examples.slice(0,e):[]}catch(s){return console.warn("AxSynth: Edge case generation failed:",s),[]}}async labelInput(e){return await new xe(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var $o=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new yn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,s=[...n.examples??[]];if(n.useTraces!==!1){let T=(await this.getTraces()).filter(v=>v.input&&v.output).map(v=>({...v.input,...v.output}));s=[...s,...T]}if(n.generateExamples||s.length===0){let I=n.synthCount??20,T={teacher:r,...n.synthOptions},R=(await new In(this.gen.getSignature(),T).generate(I)).examples.map(C=>({...C.input,...C.expected}));s=[...s,...R]}if(s.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...s].sort(()=>Math.random()-.5),c=Math.floor(l.length*(1-a)),u=l.slice(0,c),p=l.slice(c),d=n.metric;if(!d){let I={ai:r,criteria:n.criteria,...n.judgeOptions};d=new An(this.gen.getSignature(),I).toMetricFn()}let m=new bn({studentAI:r,numTrials:o,minibatch:!0,minibatchSize:10}),g=o*Math.max(u.length,10),h=await m.compile(this.gen,u,d,{validationExamples:p,maxMetricCalls:g});if(!h.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");h.optimizedProgram.instruction&&this.gen.setInstruction(h.optimizedProgram.instruction),this.currentScore=h.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,A=f,y=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,b={type:"checkpoint",name:this.options.name,version:y,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:o,trainingExamples:u.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,b),{score:f,improvement:A,checkpointVersion:y,stats:{trainingExamples:u.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var Lo=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let s={};return t.forEach(a=>{let l=a.split("."),c=o.row;for(let p of l)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);s[u]=c}),s}).filter(o=>Object.keys(o).length!==0)}};var kl=Pn(require("crypto"),1);function si(i){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:i}}function $t(i){return JSON.parse(JSON.stringify(i))}function Su(i){return Math.ceil(i.length/4)}function ii(i,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:s=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),u=l??new Set;for(let p of e){if(!p.section)continue;if(!i.sections[p.section]){if(!s)continue;i.sections[p.section]=[]}let d=i.sections[p.section];switch(p.type){case"ADD":{if(d.length>=o){if(!a)continue;let h=Ou(d,u);if(!h)continue;n.push(h.id),r.push({type:"REMOVE",section:p.section,bulletId:h.id,metadata:{...h.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??vu(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:p.metadata?{...p.metadata}:void 0};d.push(g),n.push(m);break}case"UPDATE":{let m=d.find(g=>g.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=c,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(g=>g.id===p.bulletId);if(m>=0){let[g]=d.splice(m,1);g&&n.push(g.id)}break}}}return ci(i),i.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function ai(i,e,t){for(let n of Object.values(i.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),ci(i);return}}}function pr(i){let e=i.description?`## Context Playbook
|
|
498
498
|
${i.description.trim()}
|
|
499
499
|
`:`## Context Playbook
|
|
500
500
|
`,t=Object.entries(i.sections).map(([n,r])=>{let o=r.map(s=>`- [${s.id}] ${s.content}`).join(`
|
|
@@ -505,9 +505,9 @@ _(empty)_`}).join(`
|
|
|
505
505
|
`);return`${e}
|
|
506
506
|
${t}`.trim()}function vu(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=kl.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Ou(i,e){let t=-1,n;for(let o=0;o<i.length;o+=1){let s=i[o];if(e.has(s.id))continue;let a=s.helpfulCount??0,l=s.harmfulCount??0,c=a-l*2,u=Date.parse(s.updatedAt??s.createdAt),p=[c,a,Number.isFinite(u)?u:Number.POSITIVE_INFINITY];if(!n){t=o,n=p;continue}let d=i[t],m=d.helpfulCount??0,g=d.harmfulCount??0,h=m-g*2,f=Date.parse(d.updatedAt??d.createdAt),A=[h,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(p[0]<A[0]||p[0]===A[0]&&p[1]<A[1]||p[0]===A[0]&&p[1]===A[1]&&p[2]<A[2])&&(t=o,n=p)}if(t===-1)return;let[r]=i.splice(t,1);return r}function li(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,o=[];for(let s of n){let a=s.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=s.helpfulCount,l.harmfulCount+=s.harmfulCount,l.updatedAt=s.updatedAt):(r.set(a,s),o.push(s))}i.sections[t]=o}ci(i)}function ci(i){let e=0,t=0,n=0,r=0;for(let o of Object.values(i.sections))for(let s of o)e+=1,t+=s.helpfulCount,n+=s.harmfulCount,r+=Su(s.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var ku={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},dr=class extends pt{playbook;artifact;baseInstruction;constructor(e){super({bestScore:e.bestScore,stats:e.stats,instruction:e.instruction,demos:e.demos,examples:e.examples,modelConfig:e.modelConfig,optimizerType:e.optimizerType,optimizationTime:e.optimizationTime,totalRounds:e.totalRounds,converged:e.converged,scoreHistory:e.scoreHistory,configurationHistory:e.configurationHistory}),this.playbook=$t(e.playbook),this.artifact=e.artifact,this.baseInstruction=e.baseInstruction}applyTo(e){super.applyTo(e);let t=e.getSignature(),r=[(this.baseInstruction??t.getDescription()??"").trim(),"",pr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
|
|
507
507
|
|
|
508
|
-
`);e.setDescription(r)}},
|
|
508
|
+
`);e.setDescription(r)}},Do=class extends De{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...ku,...t},this.playbook=t?.initialPlaybook!==void 0?$t(t.initialPlaybook):si()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?$t(this.aceConfig.initialPlaybook):si(),this.generatorHistory=[],this.deltaHistory=[]}configureAuto(e){switch(e){case"light":this.aceConfig.maxEpochs=1,this.aceConfig.maxReflectorRounds=1;break;case"medium":this.aceConfig.maxEpochs=2,this.aceConfig.maxReflectorRounds=2;break;case"heavy":this.aceConfig.maxEpochs=3,this.aceConfig.maxReflectorRounds=3;break}}async compile(e,t,n,r){let o=r?.aceOptions;o&&(Object.assign(this.aceConfig,{maxEpochs:o.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:o.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:o.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:o.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:o.allowDynamicSections??this.aceConfig.allowDynamicSections}),o.initialPlaybook&&(this.playbook=$t(o.initialPlaybook)));let s=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let A=0;A<p;A++)for(let x=0;x<t.length;x++){let y=t[x],b=this.composeInstruction(a??l,this.playbook);e.setDescription?.(b);let I=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let T=await n({prediction:I,example:y});typeof T=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,T),c=Math.max(c,T));let v=I?.severity,k=y?.severity,R=this.createGeneratorOutput(I,y),C=k&&v&&k!==v,O=await this.runReflectionRounds({example:y,generatorOutput:R,feedback:k&&v&&k!==v?`Expected severity "${k}" but model predicted "${v}".`:void 0}),w=await this.runCurator({program:e,example:y,reflection:O,playbook:this.playbook}),E=this.normalizeCuratorOperations(w?.operations);E.length===0&&C&&(E=this.inferOperationsFromReflection(O)),E=this.resolveCuratorOperationTargets(E,this.playbook,O,R);let S=w||E.length>0?{...w??{},operations:E}:void 0,F=[];if(E.length>0){let j=this.collectProtectedBulletIds(E),J=ii(this.playbook,E,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:j});F=J.updatedBulletIds,J.autoRemoved.length>0&&(E.push(...J.autoRemoved),S&&(S.operations=E))}if(O?.bulletTags)for(let j of O.bulletTags)ai(this.playbook,j.id,j.tag);E.length>0&&F.length>0&&li(this.playbook,this.aceConfig.similarityThreshold);let $={example:y,prediction:I,score:typeof T=="number"?T:0,generatorOutput:R,reflection:O,curator:S,timestamp:new Date().toISOString()};this.generatorHistory.push($),F.length>0&&S?.operations?.length&&this.deltaHistory.push({epoch:A,exampleIndex:x,operations:S.operations}),u+=1,this.currentRound=u;let M=typeof T=="number"&&Number.isFinite(T)?T:0,P=Number.isFinite(c)?c:M,V={...r??{},maxIterations:d};await this.updateOptimizationProgress(u,M,{epoch:A,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},P,{playbookBullets:this.playbook.stats.bulletCount},void 0,V),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,M)}}finally{e.setDescription?.(l)}let m=Date.now()-s;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let g={playbook:$t(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},h=new dr({baseInstruction:a??l,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:u,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:h,playbook:$t(this.playbook),artifact:g}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,o=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),s=await this.runCurator({program:this.program,example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(s?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let c=s||a.length>0?{...s??{},operations:a}:void 0;if(o?.bulletTags)for(let p of o.bulletTags)ai(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=ii(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),li(this.playbook,this.aceConfig.similarityThreshold)}let u={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:o,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(u),c}composeInstruction(e,t){return[e.trim(),"",pr(t)].filter(r=>r.trim().length>0).join(`
|
|
509
509
|
|
|
510
|
-
`)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],s=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(s.has(u))return;let d=this.locateBullet(t,u);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let u of n?.bulletTags??[]){let p=u.tag==="harmful"?"harmful":"primary";l(u.id,p)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let p=a.get(u);if(!p)return this.locateFallbackBullet(t,u,s);let d=g=>{for(;g.length>0;){let h=g.shift();if(!s.has(h))return h}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,s)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,s.add(p))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||o.push(u)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",p=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,h=[a,c,p,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(f.metadata={...A}),t.push(f)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,s)=>{if(!s)return;let a=s.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${o}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let s=0;s<r;s++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(s,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:pr(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),s=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await o.forward(s,{playbook:JSON.stringify({markdown:pr(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=le().input("question",le.string("Original task input serialized as JSON")).input("generator_answer",le.string("Generator output serialized as JSON")).input("generator_reasoning",le.string("Generator reasoning trace").optional()).input("playbook",le.string("Current context playbook rendered as markdown")).input("expected_answer",le.string("Expected output when ground truth is available").optional()).input("feedback",le.string("External feedback or reward signal").optional()).input("previous_reflection",le.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",le.string("Step-by-step analysis of generator performance")).output("errorIdentification",le.string("Specific mistakes detected")).output("rootCauseAnalysis",le.string("Underlying cause of the error")).output("correctApproach",le.string("What the generator should do differently")).output("keyInsight",le.string("Reusable insight to remember")).output("bulletTags",le.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Me(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=le().input("playbook",le.string("Current playbook serialized as JSON")).input("reflection",le.string("Latest reflection output serialized as JSON")).input("question_context",le.string("Original task input serialized as JSON")).input("token_budget",le.number("Approximate token budget for curator response").optional()).output("reasoning",le.string("Justification for the proposed updates")).output("operations",le.json("List of operations with type/section/content fields")).build();this.curatorProgram=Me(e)}return this.curatorProgram}};var Tn=class extends Le{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Eu([...t],this.maxExamples),u=this.traces.length;for(let p=0;p<c.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=c.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(A=>A!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let A={...l,maxRetries:1};f=await e.forward(h,m,A),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(A){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${A instanceof Error?A.message:"Unknown error"}`),f={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let s=Mu(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Mu(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var Eu=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};var Go=class extends Le{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(E,S)=>{try{s.setAllNodeInstructions?.(E);let F=await s.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:F,example:S})||{}}catch{return{}}},g=async(E,S)=>{let F=[];for(let $ of S)F.push(await m(E,$));return No(F)},h={};for(let E of a)h[E.name]=await this.getBaseInstruction(E.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,u)}],A=E=>{let S=r?.paretoMetricKey,F=r?.paretoScalarize;if(typeof F=="function")return F(E);if(S)return Number.isFinite(E[S])?E[S]:0;let $=Object.values(E);return $.length?$.reduce((M,P)=>M+P,0)/$.length:0},x=[],y=async(E,S)=>{let F=[];for(let $ of S){let M=await m(E,$);F.push(A(M))}return F};x.push(await y(h,u));let b=dt(f.map((E,S)=>({idx:S,scores:E.scores})),this.tieEpsilon).map(E=>E.idx),I=0,T=new Set,v=r?.maxMetricCalls;if(!Number.isFinite(v)||v<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let k=Math.floor(v);for(let E=0;E<this.numTrials&&!(k!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(k)));E++){let S=x[0]?.length??0,F=[];for(let z=0;z<S;z++){let ie=Number.NEGATIVE_INFINITY,G=new Set;for(let U=0;U<x.length;U++){let Y=x[U][z];Y>ie+this.tieEpsilon?(ie=Y,G.clear(),G.add(U)):Math.abs(Y-ie)<=this.tieEpsilon&&G.add(U)}F.push(G)}let $=x.map(z=>Nt(z));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let z=cr(F,$),ie=new Set;for(let N of z)for(let D of N)ie.add(D);let G=Array.from(ie),U=N=>{let D=[],_=N;for(;_!==void 0;)D.push(_),_=f[_]?.parent;return D},Y=N=>N.length?N[Math.floor(this.rand()*N.length)]:void 0,te;for(let N=0;N<10&&!te&&!(G.length<2);N++){let D=Y(G),_=Y(G);if(D===_)continue;_<D&&([D,_]=[_,D]);let B=new Set(U(D)),X=new Set(U(_));if(B.has(_)||X.has(D))continue;let pe=[...B].filter(ue=>X.has(ue));if(pe.length===0)continue;let Z=[];for(let ue of pe){let mt=f[ue].cfg,At=f[D].cfg,Ze=f[_].cfg,yt=!1,bt=new Set([...Object.keys(mt),...Object.keys(At),...Object.keys(Ze)]);for(let gt of bt){let It=mt[gt],vt=At[gt],H=Ze[gt];if(vt===It&&H!==vt||H===It&&vt!==H){yt=!0;break}}yt&&Z.push(ue)}if(Z.length===0)continue;let re=Z.map(ue=>Math.max(1e-9,$[ue])),se=this.rand()*re.reduce((ue,mt)=>ue+mt,0),ce=Z[Z.length-1];for(let ue=0;ue<Z.length;ue++){if(se<re[ue]){ce=Z[ue];break}se-=re[ue]}let be=$[ce],we=$[D],ze=$[_];if(be>Math.min(we,ze))continue;let Pe=`${D}|${_}|${ce}`;if(this.mergeAttemptKeys.has(Pe))continue;this.mergeAttemptKeys.add(Pe);let Ue=`${D}|${_}|${ce}`;T.has(Ue)||(te={i:D,j:_,a:ce})}if(this.lastIterFoundNewProgram=!1,te){let{i:N,j:D,a:_}=te,{cfg:B,descSig:X}=this.systemAwareMergeWithSig(f,N,D,(H,he)=>$[H]>=$[he]?H:he),pe=`${Math.min(N,D)}|${Math.max(N,D)}|${X}`;if(this.mergeCompositionKeys.has(pe))continue;this.mergeCompositionKeys.add(pe);let Z=x[N],re=x[D],se=Array.from({length:Z.length},(H,he)=>he),ce=se.filter(H=>(Z[H]??0)>(re[H]??0)),be=se.filter(H=>(re[H]??0)>(Z[H]??0)),we=se.filter(H=>!(ce.includes(H)||be.includes(H))),ze=5,Pe=Math.ceil(ze/3),Ue=(H,he)=>{if(he<=0||H.length===0)return[];if(H.length<=he)return[...H];let lt=[],Be=new Set;for(;lt.length<he;){let je=Math.floor(this.rand()*H.length);Be.has(je)||(Be.add(je),lt.push(H[je]))}return lt},ue=[];ue.push(...Ue(ce,Math.min(Pe,ce.length))),ue.push(...Ue(be,Math.min(Pe,be.length)));let mt=ze-ue.length;ue.push(...Ue(we,Math.max(0,mt)));let At=ze-ue.length;if(At>0){let H=se.filter(he=>!ue.includes(he));ue.push(...Ue(H,Math.min(At,H.length)))}let Ze=ue.slice(0,Math.min(ze,se.length)),yt=Ze.map(H=>u[H]),gt=(await y(B,yt)).reduce((H,he)=>H+he,0),It=Ze.reduce((H,he)=>H+(Z[he]??0),0),vt=Ze.reduce((H,he)=>H+(re[he]??0),0);if(gt>=Math.max(It,vt)+this.tieEpsilon){let H=await g(B,u);f.push({cfg:B,parent:_,scores:H}),x.push(await y(B,u));let he=b.length,lt=Ye(b.map(je=>f[je].scores))??0;b=dt(f.map((je,xr)=>({idx:xr,scores:je.scores})),this.tieEpsilon).map(je=>je.idx);let Be=Ye(b.map(je=>f[je].scores))??0;(b.length>he||Be>lt+1e-6)&&(I=0),this.mergesDue-=1,this.totalMergesTested+=1,T.add(`${Math.min(N,D)}|${Math.max(N,D)}|${_}`)}continue}}let M=ur(F,$,()=>this.rand());this.lastIterFoundNewProgram=!1;let P=this.minibatch?this.nextMinibatchIndices(p.length,E).map(z=>p[z]):p;if(r?.skipPerfectScore??!0){let z=Number(r?.perfectScore??1),ie=await y(f[M].cfg,P);if(ie.length>0&&ie.every(G=>G>=z))continue}let V=!1,j={...f[M].cfg},J="reflective_mutation",Q=E%a.length,ne=a[Q],ee,Ie;if(V&&this.mergesUsed<this.mergeMax){let z=(M+1)%f.length,ie=N=>{let D=[],_=N;for(;_!==void 0;)D.push(_),_=f[_]?.parent;return D},G=ie(M),U=ie(z),Y=G.find(N=>U.includes(N)),te=!0;if(Y||(te=!1),(U.includes(M)||G.includes(z))&&(te=!1),te){let N=f[Y].cfg,D=f[M].cfg,_=f[z].cfg,B=!1,X=new Set([...Object.keys(N),...Object.keys(D),...Object.keys(_)]);for(let pe of X){let Z=N[pe],re=D[pe],se=_[pe];if(re===Z&&se!==re||se===Z&&re!==se){B=!0;break}}B||(te=!1)}if(te){let N=Math.min(M,z),D=Math.max(M,z),_=`${N}|${D}|${Y}`;if(!T.has(_)){let B=A(f[Y].scores),X=A(f[M].scores),pe=A(f[z].scores);B<=Math.min(X,pe)&&(j=this.systemAwareMerge(f,M,z,(Z,re)=>{let se=A(f[Z].scores),ce=A(f[re].scores);return se>=ce?Z:re}),J="system_merge",this.mergesUsed+=1,T.add(_))}}else{let N=f[M].cfg[ne.name],D=r?.gepaAdapter,_;if(D)try{let B=await D.evaluate(P,{...f[M].cfg},!0);ee=Array.isArray(B?.scores)?B.scores.reduce((re,se)=>re+(Number(se)||0),0):void 0;let X=D.make_reflective_dataset({...f[M].cfg},B,[ne.name]),Z=(await D.propose_new_texts?.({...f[M].cfg},X,[ne.name]))?.[ne.name];typeof Z=="string"&&Z.length>0&&(_=Z)}catch{}if(_||(_=await this.reflectModuleInstruction(ne.name,N,s,a,{...f[M].cfg},P,async({prediction:B,example:X})=>{let pe=await n({prediction:B,example:X}),Z=Object.values(pe||{});return Z.length?Z.reduce((re,se)=>re+se,0)/Z.length:0},r)),j[ne.name]=_,D&&ee!==void 0)try{let B=await D.evaluate(P,j,!1);Ie=Array.isArray(B?.scores)?B.scores.reduce((X,pe)=>X+(Number(pe)||0),0):void 0}catch{}}}else{let z=f[M].cfg[ne.name],ie=r?.gepaAdapter,G;if(ie)try{let U=await ie.evaluate(P,{...f[M].cfg},!0);ee=Array.isArray(U?.scores)?U.scores.reduce((D,_)=>D+(Number(_)||0),0):void 0;let Y=ie.make_reflective_dataset({...f[M].cfg},U,[ne.name]),N=(await ie.propose_new_texts?.({...f[M].cfg},Y,[ne.name]))?.[ne.name];typeof N=="string"&&N.length>0&&(G=N)}catch{}if(G||(G=await this.reflectModuleInstruction(ne.name,z,s,a,{...f[M].cfg},P,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((D,_)=>D+_,0)/N.length:0},r)),j[ne.name]=G,ie&&ee!==void 0)try{let U=await ie.evaluate(P,j,!1);Ie=Array.isArray(U?.scores)?U.scores.reduce((Y,te)=>Y+(Number(te)||0),0):void 0}catch{}}let me=await y(f[M].cfg,P),Ee=await y(j,P),Xe=me.reduce((z,ie)=>z+ie,0),Te=Ee.reduce((z,ie)=>z+ie,0);if(this.currentRound=E+1,await this.updateOptimizationProgress(this.currentRound,Te,{modules:a.length,mutatedModule:ne.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:J,paretoSetSize:u.length},Te,{idx:M},{...r??{},maxIterations:this.numTrials}),!(Te>Xe+this.tieEpsilon&&(ee===void 0||Ie===void 0||Ie>ee+this.tieEpsilon))){if(++I>=this.earlyStoppingTrials)break;continue}let De=await g(j,u);f.push({cfg:j,parent:M,scores:De}),x.push(await y(j,u));let xt=b.length,ye=Ye(b.map(z=>f[z].scores))??0;b=dt(f.map((z,ie)=>({idx:ie,scores:z.scores})),this.tieEpsilon).map(z=>z.idx);let Ge=Ye(b.map(z=>f[z].scores))??0;if(b.length>xt||Ge>ye+1e-6)I=0;else if(I++,I>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=dt(f.map((E,S)=>({idx:S,scores:E.scores})),this.tieEpsilon),C=R.length>0?Math.max(...R.map(E=>A(E.scores))):0,O=Ye(R.map(E=>E.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);return this.recordParetoMetrics(R.length,f.length,"GEPA-Flow",O,w),{demos:[],stats:this.stats,bestScore:C,paretoFront:R.map(E=>({demos:[],scores:E.scores,configuration:{candidate:E.idx},dominatedSolutions:E.dominated})),paretoFrontSize:R.length,hypervolume:O,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Nt(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],u=[];for(let A of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,A,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:x,example:A});u.push({input:A,prediction:x,score:typeof y=="number"?y:0})}catch{u.push({input:A,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=Me('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let A of u){let x=g({prediction:A.prediction,example:A.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let h="";try{h=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=Me('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let x=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:h,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=f=>{let A=[],x=f;for(;x!==void 0;)A.push(x),x=e[x]?.parent;return A},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of h){let A=u[f],x=p[f],y=d[f];if(x===A&&y!==x)m[f]=y,g.push("j");else if(y===A&&x!==y)m[f]=x,g.push("i");else if(x!==y&&x!==A&&y!==A){let b=r(t,n);m[f]=b===t?x:y,g.push(b===t?"i":"j")}else m[f]=x??y??A,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=h=>{let f=[],A=h;for(;A!==void 0;)f.push(A),A=e[A]?.parent;return f},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)]);for(let h of g){let f=u[h],A=p[h],x=d[h];if(A===f&&x!==A)m[h]=x;else if(x===f&&A!==x)m[h]=A;else if(A!==x&&A!==f&&x!==f){let y=r(t,n);m[h]=y===t?A:x}else m[h]=A??x??f}return m}};var Uo=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Bo=class extends Le{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 Uo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
|
|
510
|
+
`)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],s=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(s.has(u))return;let d=this.locateBullet(t,u);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let u of n?.bulletTags??[]){let p=u.tag==="harmful"?"harmful":"primary";l(u.id,p)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let p=a.get(u);if(!p)return this.locateFallbackBullet(t,u,s);let d=g=>{for(;g.length>0;){let h=g.shift();if(!s.has(h))return h}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,s)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,s.add(p))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||o.push(u)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",p=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,h=[a,c,p,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(f.metadata={...A}),t.push(f)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,s)=>{if(!s)return;let a=s.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${o}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let s=0;s<r;s++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(s,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:pr(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),s=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await o.forward(s,{playbook:JSON.stringify({markdown:pr(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=le().input("question",le.string("Original task input serialized as JSON")).input("generator_answer",le.string("Generator output serialized as JSON")).input("generator_reasoning",le.string("Generator reasoning trace").optional()).input("playbook",le.string("Current context playbook rendered as markdown")).input("expected_answer",le.string("Expected output when ground truth is available").optional()).input("feedback",le.string("External feedback or reward signal").optional()).input("previous_reflection",le.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",le.string("Step-by-step analysis of generator performance")).output("errorIdentification",le.string("Specific mistakes detected")).output("rootCauseAnalysis",le.string("Underlying cause of the error")).output("correctApproach",le.string("What the generator should do differently")).output("keyInsight",le.string("Reusable insight to remember")).output("bulletTags",le.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Me(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=le().input("playbook",le.string("Current playbook serialized as JSON")).input("reflection",le.string("Latest reflection output serialized as JSON")).input("question_context",le.string("Original task input serialized as JSON")).input("token_budget",le.number("Approximate token budget for curator response").optional()).output("reasoning",le.string("Justification for the proposed updates")).output("operations",le.json("List of operations with type/section/content fields")).build();this.curatorProgram=Me(e)}return this.curatorProgram}};var Tn=class extends De{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Eu([...t],this.maxExamples),u=this.traces.length;for(let p=0;p<c.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=c.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(A=>A!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let A={...l,maxRetries:1};f=await e.forward(h,m,A),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(A){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${A instanceof Error?A.message:"Unknown error"}`),f={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-u;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let s=Mu(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Mu(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var Eu=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};var Go=class extends De{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(E,S)=>{try{s.setAllNodeInstructions?.(E);let F=await s.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:F,example:S})||{}}catch{return{}}},g=async(E,S)=>{let F=[];for(let $ of S)F.push(await m(E,$));return No(F)},h={};for(let E of a)h[E.name]=await this.getBaseInstruction(E.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,u)}],A=E=>{let S=r?.paretoMetricKey,F=r?.paretoScalarize;if(typeof F=="function")return F(E);if(S)return Number.isFinite(E[S])?E[S]:0;let $=Object.values(E);return $.length?$.reduce((M,P)=>M+P,0)/$.length:0},x=[],y=async(E,S)=>{let F=[];for(let $ of S){let M=await m(E,$);F.push(A(M))}return F};x.push(await y(h,u));let b=dt(f.map((E,S)=>({idx:S,scores:E.scores})),this.tieEpsilon).map(E=>E.idx),I=0,T=new Set,v=r?.maxMetricCalls;if(!Number.isFinite(v)||v<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let k=Math.floor(v);for(let E=0;E<this.numTrials&&!(k!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(k)));E++){let S=x[0]?.length??0,F=[];for(let z=0;z<S;z++){let ie=Number.NEGATIVE_INFINITY,G=new Set;for(let U=0;U<x.length;U++){let Y=x[U][z];Y>ie+this.tieEpsilon?(ie=Y,G.clear(),G.add(U)):Math.abs(Y-ie)<=this.tieEpsilon&&G.add(U)}F.push(G)}let $=x.map(z=>Nt(z));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let z=cr(F,$),ie=new Set;for(let N of z)for(let L of N)ie.add(L);let G=Array.from(ie),U=N=>{let L=[],_=N;for(;_!==void 0;)L.push(_),_=f[_]?.parent;return L},Y=N=>N.length?N[Math.floor(this.rand()*N.length)]:void 0,te;for(let N=0;N<10&&!te&&!(G.length<2);N++){let L=Y(G),_=Y(G);if(L===_)continue;_<L&&([L,_]=[_,L]);let B=new Set(U(L)),X=new Set(U(_));if(B.has(_)||X.has(L))continue;let pe=[...B].filter(ue=>X.has(ue));if(pe.length===0)continue;let Z=[];for(let ue of pe){let mt=f[ue].cfg,At=f[L].cfg,Ze=f[_].cfg,yt=!1,bt=new Set([...Object.keys(mt),...Object.keys(At),...Object.keys(Ze)]);for(let gt of bt){let It=mt[gt],vt=At[gt],H=Ze[gt];if(vt===It&&H!==vt||H===It&&vt!==H){yt=!0;break}}yt&&Z.push(ue)}if(Z.length===0)continue;let re=Z.map(ue=>Math.max(1e-9,$[ue])),se=this.rand()*re.reduce((ue,mt)=>ue+mt,0),ce=Z[Z.length-1];for(let ue=0;ue<Z.length;ue++){if(se<re[ue]){ce=Z[ue];break}se-=re[ue]}let be=$[ce],we=$[L],ze=$[_];if(be>Math.min(we,ze))continue;let Pe=`${L}|${_}|${ce}`;if(this.mergeAttemptKeys.has(Pe))continue;this.mergeAttemptKeys.add(Pe);let Ue=`${L}|${_}|${ce}`;T.has(Ue)||(te={i:L,j:_,a:ce})}if(this.lastIterFoundNewProgram=!1,te){let{i:N,j:L,a:_}=te,{cfg:B,descSig:X}=this.systemAwareMergeWithSig(f,N,L,(H,he)=>$[H]>=$[he]?H:he),pe=`${Math.min(N,L)}|${Math.max(N,L)}|${X}`;if(this.mergeCompositionKeys.has(pe))continue;this.mergeCompositionKeys.add(pe);let Z=x[N],re=x[L],se=Array.from({length:Z.length},(H,he)=>he),ce=se.filter(H=>(Z[H]??0)>(re[H]??0)),be=se.filter(H=>(re[H]??0)>(Z[H]??0)),we=se.filter(H=>!(ce.includes(H)||be.includes(H))),ze=5,Pe=Math.ceil(ze/3),Ue=(H,he)=>{if(he<=0||H.length===0)return[];if(H.length<=he)return[...H];let lt=[],Be=new Set;for(;lt.length<he;){let je=Math.floor(this.rand()*H.length);Be.has(je)||(Be.add(je),lt.push(H[je]))}return lt},ue=[];ue.push(...Ue(ce,Math.min(Pe,ce.length))),ue.push(...Ue(be,Math.min(Pe,be.length)));let mt=ze-ue.length;ue.push(...Ue(we,Math.max(0,mt)));let At=ze-ue.length;if(At>0){let H=se.filter(he=>!ue.includes(he));ue.push(...Ue(H,Math.min(At,H.length)))}let Ze=ue.slice(0,Math.min(ze,se.length)),yt=Ze.map(H=>u[H]),gt=(await y(B,yt)).reduce((H,he)=>H+he,0),It=Ze.reduce((H,he)=>H+(Z[he]??0),0),vt=Ze.reduce((H,he)=>H+(re[he]??0),0);if(gt>=Math.max(It,vt)+this.tieEpsilon){let H=await g(B,u);f.push({cfg:B,parent:_,scores:H}),x.push(await y(B,u));let he=b.length,lt=Ye(b.map(je=>f[je].scores))??0;b=dt(f.map((je,xr)=>({idx:xr,scores:je.scores})),this.tieEpsilon).map(je=>je.idx);let Be=Ye(b.map(je=>f[je].scores))??0;(b.length>he||Be>lt+1e-6)&&(I=0),this.mergesDue-=1,this.totalMergesTested+=1,T.add(`${Math.min(N,L)}|${Math.max(N,L)}|${_}`)}continue}}let M=ur(F,$,()=>this.rand());this.lastIterFoundNewProgram=!1;let P=this.minibatch?this.nextMinibatchIndices(p.length,E).map(z=>p[z]):p;if(r?.skipPerfectScore??!0){let z=Number(r?.perfectScore??1),ie=await y(f[M].cfg,P);if(ie.length>0&&ie.every(G=>G>=z))continue}let V=!1,j={...f[M].cfg},J="reflective_mutation",Q=E%a.length,ne=a[Q],ee,Ie;if(V&&this.mergesUsed<this.mergeMax){let z=(M+1)%f.length,ie=N=>{let L=[],_=N;for(;_!==void 0;)L.push(_),_=f[_]?.parent;return L},G=ie(M),U=ie(z),Y=G.find(N=>U.includes(N)),te=!0;if(Y||(te=!1),(U.includes(M)||G.includes(z))&&(te=!1),te){let N=f[Y].cfg,L=f[M].cfg,_=f[z].cfg,B=!1,X=new Set([...Object.keys(N),...Object.keys(L),...Object.keys(_)]);for(let pe of X){let Z=N[pe],re=L[pe],se=_[pe];if(re===Z&&se!==re||se===Z&&re!==se){B=!0;break}}B||(te=!1)}if(te){let N=Math.min(M,z),L=Math.max(M,z),_=`${N}|${L}|${Y}`;if(!T.has(_)){let B=A(f[Y].scores),X=A(f[M].scores),pe=A(f[z].scores);B<=Math.min(X,pe)&&(j=this.systemAwareMerge(f,M,z,(Z,re)=>{let se=A(f[Z].scores),ce=A(f[re].scores);return se>=ce?Z:re}),J="system_merge",this.mergesUsed+=1,T.add(_))}}else{let N=f[M].cfg[ne.name],L=r?.gepaAdapter,_;if(L)try{let B=await L.evaluate(P,{...f[M].cfg},!0);ee=Array.isArray(B?.scores)?B.scores.reduce((re,se)=>re+(Number(se)||0),0):void 0;let X=L.make_reflective_dataset({...f[M].cfg},B,[ne.name]),Z=(await L.propose_new_texts?.({...f[M].cfg},X,[ne.name]))?.[ne.name];typeof Z=="string"&&Z.length>0&&(_=Z)}catch{}if(_||(_=await this.reflectModuleInstruction(ne.name,N,s,a,{...f[M].cfg},P,async({prediction:B,example:X})=>{let pe=await n({prediction:B,example:X}),Z=Object.values(pe||{});return Z.length?Z.reduce((re,se)=>re+se,0)/Z.length:0},r)),j[ne.name]=_,L&&ee!==void 0)try{let B=await L.evaluate(P,j,!1);Ie=Array.isArray(B?.scores)?B.scores.reduce((X,pe)=>X+(Number(pe)||0),0):void 0}catch{}}}else{let z=f[M].cfg[ne.name],ie=r?.gepaAdapter,G;if(ie)try{let U=await ie.evaluate(P,{...f[M].cfg},!0);ee=Array.isArray(U?.scores)?U.scores.reduce((L,_)=>L+(Number(_)||0),0):void 0;let Y=ie.make_reflective_dataset({...f[M].cfg},U,[ne.name]),N=(await ie.propose_new_texts?.({...f[M].cfg},Y,[ne.name]))?.[ne.name];typeof N=="string"&&N.length>0&&(G=N)}catch{}if(G||(G=await this.reflectModuleInstruction(ne.name,z,s,a,{...f[M].cfg},P,async({prediction:U,example:Y})=>{let te=await n({prediction:U,example:Y}),N=Object.values(te||{});return N.length?N.reduce((L,_)=>L+_,0)/N.length:0},r)),j[ne.name]=G,ie&&ee!==void 0)try{let U=await ie.evaluate(P,j,!1);Ie=Array.isArray(U?.scores)?U.scores.reduce((Y,te)=>Y+(Number(te)||0),0):void 0}catch{}}let me=await y(f[M].cfg,P),Ee=await y(j,P),Xe=me.reduce((z,ie)=>z+ie,0),Te=Ee.reduce((z,ie)=>z+ie,0);if(this.currentRound=E+1,await this.updateOptimizationProgress(this.currentRound,Te,{modules:a.length,mutatedModule:ne.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:J,paretoSetSize:u.length},Te,{idx:M},{...r??{},maxIterations:this.numTrials}),!(Te>Xe+this.tieEpsilon&&(ee===void 0||Ie===void 0||Ie>ee+this.tieEpsilon))){if(++I>=this.earlyStoppingTrials)break;continue}let Le=await g(j,u);f.push({cfg:j,parent:M,scores:Le}),x.push(await y(j,u));let xt=b.length,ye=Ye(b.map(z=>f[z].scores))??0;b=dt(f.map((z,ie)=>({idx:ie,scores:z.scores})),this.tieEpsilon).map(z=>z.idx);let Ge=Ye(b.map(z=>f[z].scores))??0;if(b.length>xt||Ge>ye+1e-6)I=0;else if(I++,I>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=dt(f.map((E,S)=>({idx:S,scores:E.scores})),this.tieEpsilon),C=R.length>0?Math.max(...R.map(E=>A(E.scores))):0,O=Ye(R.map(E=>E.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);return this.recordParetoMetrics(R.length,f.length,"GEPA-Flow",O,w),{demos:[],stats:this.stats,bestScore:C,paretoFront:R.map(E=>({demos:[],scores:E.scores,configuration:{candidate:E.idx},dominatedSolutions:E.dominated})),paretoFrontSize:R.length,hypervolume:O,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Nt(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],u=[];for(let A of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,A,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:x,example:A});u.push({input:A,prediction:x,score:typeof y=="number"?y:0})}catch{u.push({input:A,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=Me('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let A of u){let x=g({prediction:A.prediction,example:A.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let h="";try{h=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=Me('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let x=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:h,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=f=>{let A=[],x=f;for(;x!==void 0;)A.push(x),x=e[x]?.parent;return A},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of h){let A=u[f],x=p[f],y=d[f];if(x===A&&y!==x)m[f]=y,g.push("j");else if(y===A&&x!==y)m[f]=x,g.push("i");else if(x!==y&&x!==A&&y!==A){let b=r(t,n);m[f]=b===t?x:y,g.push(b===t?"i":"j")}else m[f]=x??y??A,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=h=>{let f=[],A=h;for(;A!==void 0;)f.push(A),A=e[A]?.parent;return f},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)]);for(let h of g){let f=u[h],A=p[h],x=d[h];if(A===f&&x!==A)m[h]=x;else if(x===f&&A!==x)m[h]=A;else if(A!==x&&A!==f&&x!==f){let y=r(t,n);m[h]=y===t?A:x}else m[h]=A??x??f}return m}};var Uo=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Bo=class extends De{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 Uo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
|
|
511
511
|
Analyze this language model program and provide a concise summary of its purpose and structure.
|
|
512
512
|
|
|
513
513
|
Program Signature: ${e.getSignature()}
|
|
@@ -633,7 +633,7 @@ ${e}
|
|
|
633
633
|
`),r+=`${e}
|
|
634
634
|
`;break;default:r=JSON.stringify(n,null,2)}i(r)}},Pl=mr(),Fl=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 r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var On=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},jo=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var gr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new wn;program;flowName;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),u=this.getStepMetadata(l,a),p=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,f=Object.keys(o).filter(x=>!p.includes(x)),A;if(c==="execute"&&u.nodeName&&f.length>0){let x=`${u.nodeName}Result`;A=o[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,executionTime:g,state:{...o},newFields:f,result:A})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:c,nodeName:u.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted: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 r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return le().input("userInput",le.string("User input to the flow")).output("flowOutput",le.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(p=>t.add(p)),u.dependencies.forEach(p=>n.add(p));let r=new Set;for(let u of Array.from(n))t.has(u)||r.add(u);let o=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(u=>{u.startsWith("_")||o.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(p=>o.add(p))}else for(let u of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(u)){p=!0;break}if(!p)if(u.endsWith("Result")){let d=u.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let h=m.getSignature().getOutputFields();for(let f of h)o.add(f.name)}else o.add(u)}else o.add(u)}if(r.size===0&&o.size===0){let u=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let f of h.getInputFields()){let A=this.toCamelCase(`${m}_${f.name}`);u.push({name:A,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of h.getOutputFields()){let A=this.toCamelCase(`${m}_${f.name}`);p.push({name:A,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let d=new ge;return u.length>0?d.setInputFields(u):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new ge,l=[];for(let u of Array.from(r))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let u of Array.from(o))u.startsWith("_")||c.push({name:u,type:{name:"string"},description:`Output field: ${u}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){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=mr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Fl(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 St(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
|
|
635
635
|
`)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),o=async(s,a)=>{let l=a?.ai;if(!l)throw new Error("AI service is required to run the flow");let c=await this.forward(l,s??{}),u=e.getOutputFields(),p=c??{};return Object.keys(p).map(d=>{let m=u.find(g=>g.name===d);return m&&m.title?`${m.title}: ${p[d]}`:`${d}: ${p[d]}`}).join(`
|
|
636
|
-
`)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:o}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return rr(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]=rr(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){let r=n?.cachingFunction??W.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),c=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,u=_e("sha256");u.update(a.hash()??"");let p=d=>{let m=typeof d;if(u.update(`|${m}|`),d==null){u.update("null");return}if(m==="string"||m==="number"||m==="boolean"){u.update(String(d));return}if(Array.isArray(d)){u.update("[");for(let g of d)p(g);u.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let g=d;u.update(g.mimeType??"");let h=_e("sha256").update(g.data??"").digest("hex");u.update(h);return}if(typeof d=="object"){let g=d,h=Object.keys(g).sort();for(let f of h)u.update(`{${f}}`),p(g[f]);return}u.update(String(d))};for(let d of l)p(c?.[d]);return u.digest("hex")})();if(r&&o){let a;try{a=await r(o)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let s=await this.forward(e,t,n);if(r&&o)try{await r(o,s)}catch{}yield{version:1,index:0,delta:s}}async forward(e,t,n){let r=n?.cachingFunction??W.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),c=l.getInputFields().map(m=>m.name),u=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=_e("sha256");p.update(l.hash()??"");let d=m=>{let g=typeof m;if(p.update(`|${g}|`),m==null){p.update("null");return}if(g==="string"||g==="number"||g==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let h of m)d(h);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let h=m;p.update(h.mimeType??"");let f=_e("sha256").update(h.data??"").digest("hex");p.update(f);return}if(typeof m=="object"){let h=m,f=Object.keys(h).sort();for(let A of f)p.update(`{${A}}`),d(h[A]);return}p.update(String(m))};for(let m of c)d(u?.[m]);return p.digest("hex")})();if(r&&o){let l=await r(o);if(l!==void 0)return l}let s=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(A=>A.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:s,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let c=n?.tracer??this.defaultAIOptions?.tracer,u=n?.traceContext,p,d=u;if(c){let f=this.getExecutionPlan(),A=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=c.startSpan(A,{kind:kn.SpanKind.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let x=u??kn.context.active();d=kn.trace.setSpan(x,p)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),c&&(f.tracer=c),d&&(f.traceContext=d),Object.keys(f).length>0?f:void 0})()},g=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(g){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),A=await this.executeStepsWithLogging(f,a,m,!0);a=A.finalState,h=A.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,h=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-s;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(p&&p.end(),r&&o)try{await r(o,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof ge){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=Me(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await Rn(n,async(l,c)=>{let u=l(o);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(s,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(s),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,u,{...c,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),s=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await Rn(e,async(s,a)=>{let l=new On(this.nodeGenerators);return await s(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...s};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let p=r;p<o;p++){let d=this.flowDefinition[p];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,c=0;for(;n(l)&&c<r;){c++;for(let u of o)l=await u(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async 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 c=r?.batchSize||this.autoParallelConfig.batchSize;l=await Rn(a,async(u,p)=>n(u,p,s),c)}else l=a.map((c,u)=>n(c,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(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?ge.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)o=o.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)o=o.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)o=o.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)o=o.appendOutputField(s.name,s.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function qo(i){return gr.create(i)}var zo=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(s.Labels["com.example.tag"]=r);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:r}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),c=s[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),s=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;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}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var Ho=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Ko=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:o});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)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=ve(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let u=c;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:s}=await o;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function _l(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Nl(i){let t=new TextEncoder().encode(i),n=await di().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function ui(){return _l(await Nl(ve()+Math.random().toString(36)))}async function $l(i){return _l(await Nl(i))}async function Wo(i,e){let t=await fetch(i,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${i}: ${t.statusText}`);return await t.json()}function Dl(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function hr(i){return i.endsWith("/")?i.slice(0,-1):i}function Pu(i){if(!i)return null;let e=i.match(/resource_metadata\s*=\s*"([^"]+)"/i)||i.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function Ll(i,e){let t=Pu(e);if(t){let a=await Wo(t),l=hr(new URL(i).toString().split("?")[0]),c=hr(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let s;for(let a of o)try{let l=await Wo(a.url),c=hr(l.resource??""),u=hr(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:p}}catch(l){s=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(s)}`)}async function Gl(i){let e=new URL(i),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let s=await Wo(o);if(!s.authorization_endpoint||!s.token_endpoint)throw new Error("AS metadata missing endpoints");let a=s.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return s}catch(s){r=s}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Mn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await Gl(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Ll(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),s=e.currentToken??await this.getStoredToken(t,r);if(s?.accessToken&&!this.isExpired(s.expiresAt))return{token:s,issuer:r,asMeta:o,resource:t};if(s?.refreshToken)try{let x=await this.refreshToken(s.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await ui(),u=await $l(c),p=await ui(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Dl({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:u,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:h}=await this.oauth.onAuthCode(m),f=h??a,A=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw new Error("Dynamic client registration did not return client_id");return s}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let s=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);let a=await s.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var Vo=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Mn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let s=JSON.parse(o.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.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
|
|
636
|
+
`)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:o}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return rr(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]=rr(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){let r=n?.cachingFunction??W.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),c=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,u=_e("sha256");u.update(a.hash()??"");let p=d=>{let m=typeof d;if(u.update(`|${m}|`),d==null){u.update("null");return}if(m==="string"||m==="number"||m==="boolean"){u.update(String(d));return}if(Array.isArray(d)){u.update("[");for(let g of d)p(g);u.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let g=d;u.update(g.mimeType??"");let h=_e("sha256").update(g.data??"").digest("hex");u.update(h);return}if(typeof d=="object"){let g=d,h=Object.keys(g).sort();for(let f of h)u.update(`{${f}}`),p(g[f]);return}u.update(String(d))};for(let d of l)p(c?.[d]);return u.digest("hex")})();if(r&&o){let a;try{a=await r(o)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let s=await this.forward(e,t,n);if(r&&o)try{await r(o,s)}catch{}yield{version:1,index:0,delta:s}}async forward(e,t,n){let r=n?.cachingFunction??W.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),c=l.getInputFields().map(m=>m.name),u=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=_e("sha256");p.update(l.hash()??"");let d=m=>{let g=typeof m;if(p.update(`|${g}|`),m==null){p.update("null");return}if(g==="string"||g==="number"||g==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let h of m)d(h);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let h=m;p.update(h.mimeType??"");let f=_e("sha256").update(h.data??"").digest("hex");p.update(f);return}if(typeof m=="object"){let h=m,f=Object.keys(h).sort();for(let A of f)p.update(`{${A}}`),d(h[A]);return}p.update(String(m))};for(let m of c)d(u?.[m]);return p.digest("hex")})();if(r&&o){let l=await r(o);if(l!==void 0)return l}let s=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(A=>A.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:s,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let c=n?.tracer??this.defaultAIOptions?.tracer,u=n?.traceContext,p,d=u;if(c){let f=this.getExecutionPlan(),A=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=c.startSpan(A,{kind:kn.SpanKind.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let x=u??kn.context.active();d=kn.trace.setSpan(x,p)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),c&&(f.tracer=c),d&&(f.traceContext=d),Object.keys(f).length>0?f:void 0})()},g=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(g){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),A=await this.executeStepsWithLogging(f,a,m,!0);a=A.finalState,h=A.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,h=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-s;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(p&&p.end(),r&&o)try{await r(o,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof ge){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=Me(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await Rn(n,async(l,c)=>{let u=l(o);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(s,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(s),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,u,{...c,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),s=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await Rn(e,async(s,a)=>{let l=new On(this.nodeGenerators);return await s(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...s};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let p=r;p<o;p++){let d=this.flowDefinition[p];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,c=0;for(;n(l)&&c<r;){c++;for(let u of o)l=await u(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async 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 c=r?.batchSize||this.autoParallelConfig.batchSize;l=await Rn(a,async(u,p)=>n(u,p,s),c)}else l=a.map((c,u)=>n(c,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(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?ge.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)o=o.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)o=o.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)o=o.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)o=o.appendOutputField(s.name,s.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function qo(i){return gr.create(i)}var zo=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(s.Labels["com.example.tag"]=r);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:r}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),c=s[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),s=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;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}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var Ho=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Ko=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:o});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)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=ve(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let u=c;l(new Error(`RPC Error ${u.error.code}: ${u.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:s}=await o;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function _l(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Nl(i){let t=new TextEncoder().encode(i),n=await di().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function ui(){return _l(await Nl(ve()+Math.random().toString(36)))}async function $l(i){return _l(await Nl(i))}async function Wo(i,e){let t=await fetch(i,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${i}: ${t.statusText}`);return await t.json()}function Ll(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function hr(i){return i.endsWith("/")?i.slice(0,-1):i}function Pu(i){if(!i)return null;let e=i.match(/resource_metadata\s*=\s*"([^"]+)"/i)||i.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function Dl(i,e){let t=Pu(e);if(t){let a=await Wo(t),l=hr(new URL(i).toString().split("?")[0]),c=hr(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let s;for(let a of o)try{let l=await Wo(a.url),c=hr(l.resource??""),u=hr(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:p}}catch(l){s=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(s)}`)}async function Gl(i){let e=new URL(i),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let s=await Wo(o);if(!s.authorization_endpoint||!s.token_endpoint)throw new Error("AS metadata missing endpoints");let a=s.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return s}catch(s){r=s}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Mn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await Gl(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Dl(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),s=e.currentToken??await this.getStoredToken(t,r);if(s?.accessToken&&!this.isExpired(s.expiresAt))return{token:s,issuer:r,asMeta:o,resource:t};if(s?.refreshToken)try{let x=await this.refreshToken(s.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await ui(),u=await $l(c),p=await ui(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Ll({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:u,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:h}=await this.oauth.onAuthCode(m),f=h??a,A=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw new Error("Dynamic client registration did not return client_id");return s}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let s=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);let a=await s.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var Vo=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Mn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let s=JSON.parse(o.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.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
|
|
637
637
|
`);o=c.pop()||"";for(let u of c)if(u.startsWith("data: ")){let p=u.slice(6);if(p==="[DONE]")return;try{let d=JSON.parse(p);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=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let a=r.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);let o=r.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let s=r.headers.get("Content-Type");if(s?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(s?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${s}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let s=new TextDecoder,a="",l=async()=>{try{let{done:c,value:u}=await o.read();if(c){o.releaseLock();return}a+=s.decode(u,{stream:!0});let p=a.split(`
|
|
638
638
|
`);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(c){o.releaseLock(),r(c)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var Jo=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Mn(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:s,value:a}=await t.read();if(s)break;r+=n.decode(a,{stream:!0});let l=r.split(`
|
|
639
639
|
`);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))o=c.slice(7).trim();else if(c.startsWith("data: ")){let u=c.slice(6);if(o==="endpoint"){let p=u.trim(),d;try{let m=JSON.parse(p);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=p}if(!d)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(d)||(d=new URL(this.sseUrl).origin+(d.startsWith("/")?d:`/${d}`)),this.endpoint=d,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let p=u.trim();try{let d=JSON.parse(p);if(d&&typeof d=="object"&&"id"in d){let m=d.id,g=this.pendingRequests.get(m);g?(g.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else c.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function Fu(i,e,t,n,r){let o={...i};if(o.parameters){let s=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(c=>s.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){o.parameters=Nu(o.parameters,l);let c=o.func;o.func=async(u,p)=>{let d={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(d=jl(g.values,l))}else d=jl(e,l);let m={...u,...d};return await c(m,p)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=ql(o.parameters,n)),o}var Ul=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),Bl=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),fr=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:s,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:u,debug:p}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=u??[],this.debug=p,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 Ul;if(r&&r.length<100)throw Bl;this.program=new xe(o,{...l,description:r??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:_u(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=ql(this.func.parameters,d))}static create(e,t){let n=ge.create(e),{ai:r,name:o,description:s,definition:a,agents:l,functions:c,...u}=t;return new i({ai:r,name:o,description:s,definition:a,signature:n,agents:l,functions:c},u)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...s}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...r,model:o}),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(`
|