@ax-llm/ax 14.0.40 → 14.0.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.cjs +6 -6
- package/index.cjs.map +1 -1
- package/index.d.cts +20 -1
- package/index.d.ts +20 -1
- package/index.global.js +8 -8
- package/index.global.js.map +1 -1
- package/index.js +15 -15
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Pl=Object.create;var Zn=Object.defineProperty;var Fl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Dl=Object.prototype.hasOwnProperty;var $l=(i,e)=>{for(var t in e)Zn(i,t,{get:e[t],enumerable:!0})},Vs=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _l(e))!Dl.call(i,r)&&r!==t&&Zn(i,r,{get:()=>e[r],enumerable:!(n=Fl(e,r))||n.enumerable});return i};var gn=(i,e,t)=>(t=i!=null?Pl(Nl(i)):{},Vs(e||!i||!i.__esModule?Zn(t,"default",{value:i,enumerable:!0}):t,i)),Ll=i=>Vs(Zn({},"__esModule",{value:!0}),i);var pu={};$l(pu,{AxACE:()=>ho,AxACEOptimizedProgram:()=>Hn,AxAI:()=>Pn,AxAIAnthropic:()=>kt,AxAIAnthropicModel:()=>fn,AxAIAnthropicVertexModel:()=>ir,AxAIAzureOpenAI:()=>Ft,AxAICohere:()=>_t,AxAICohereEmbedModel:()=>In,AxAICohereModel:()=>bn,AxAIDeepSeek:()=>Nt,AxAIDeepSeekModel:()=>Tn,AxAIGoogleGemini:()=>Dt,AxAIGoogleGeminiEmbedModel:()=>fr,AxAIGoogleGeminiEmbedTypes:()=>rs,AxAIGoogleGeminiModel:()=>Cn,AxAIGoogleGeminiSafetyCategory:()=>Ar,AxAIGoogleGeminiSafetyThreshold:()=>xr,AxAIGrok:()=>Vt,AxAIGrokEmbedModels:()=>fs,AxAIGrokModel:()=>En,AxAIGroq:()=>Lt,AxAIGroqModel:()=>Rn,AxAIHuggingFace:()=>Gt,AxAIHuggingFaceModel:()=>Cr,AxAIMistral:()=>Ut,AxAIMistralEmbedModels:()=>ls,AxAIMistralModel:()=>wn,AxAIOllama:()=>Bt,AxAIOpenAI:()=>Pt,AxAIOpenAIBase:()=>pe,AxAIOpenAIEmbedModel:()=>Ot,AxAIOpenAIModel:()=>yn,AxAIOpenAIResponses:()=>qt,AxAIOpenAIResponsesBase:()=>Sn,AxAIOpenAIResponsesImpl:()=>jt,AxAIOpenAIResponsesModel:()=>Mt,AxAIOpenRouter:()=>zt,AxAIRefusalError:()=>ae,AxAIReka:()=>Ht,AxAIRekaModel:()=>kn,AxAIServiceAbortedError:()=>wt,AxAIServiceAuthenticationError:()=>it,AxAIServiceError:()=>Te,AxAIServiceNetworkError:()=>We,AxAIServiceResponseError:()=>tt,AxAIServiceStatusError:()=>ht,AxAIServiceStreamTerminatedError:()=>Be,AxAIServiceTimeoutError:()=>ft,AxAITogether:()=>Kt,AxAIWebLLM:()=>Wt,AxAIWebLLMModel:()=>Mn,AxAgent:()=>Yn,AxApacheTika:()=>ao,AxAssertionError:()=>Ve,AxBalancer:()=>pr,AxBaseAI:()=>de,AxBaseOptimizer:()=>Se,AxBootstrapFewShot:()=>rn,AxContentProcessingError:()=>je,AxDB:()=>$r,AxDBBase:()=>Fe,AxDBCloudflare:()=>Jt,AxDBManager:()=>Lr,AxDBMemory:()=>at,AxDBPinecone:()=>Qt,AxDBWeaviate:()=>Yt,AxDefaultCostTracker:()=>qn,AxDefaultResultReranker:()=>io,AxDockerSession:()=>Co,AxEmbeddingAdapter:()=>Ro,AxEvalUtil:()=>rl,AxFlow:()=>Jn,AxFlowDependencyAnalyzer:()=>on,AxFlowExecutionPlanner:()=>an,AxFlowSubContextImpl:()=>un,AxFlowTypedSubContextImpl:()=>Io,AxFluentFieldType:()=>
|
|
1
|
+
"use strict";var Pl=Object.create;var Zn=Object.defineProperty;var Fl=Object.getOwnPropertyDescriptor;var _l=Object.getOwnPropertyNames;var Nl=Object.getPrototypeOf,Dl=Object.prototype.hasOwnProperty;var $l=(i,e)=>{for(var t in e)Zn(i,t,{get:e[t],enumerable:!0})},Vs=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _l(e))!Dl.call(i,r)&&r!==t&&Zn(i,r,{get:()=>e[r],enumerable:!(n=Fl(e,r))||n.enumerable});return i};var gn=(i,e,t)=>(t=i!=null?Pl(Nl(i)):{},Vs(e||!i||!i.__esModule?Zn(t,"default",{value:i,enumerable:!0}):t,i)),Ll=i=>Vs(Zn({},"__esModule",{value:!0}),i);var pu={};$l(pu,{AxACE:()=>ho,AxACEOptimizedProgram:()=>Hn,AxAI:()=>Pn,AxAIAnthropic:()=>kt,AxAIAnthropicModel:()=>fn,AxAIAnthropicVertexModel:()=>ir,AxAIAzureOpenAI:()=>Ft,AxAICohere:()=>_t,AxAICohereEmbedModel:()=>In,AxAICohereModel:()=>bn,AxAIDeepSeek:()=>Nt,AxAIDeepSeekModel:()=>Tn,AxAIGoogleGemini:()=>Dt,AxAIGoogleGeminiEmbedModel:()=>fr,AxAIGoogleGeminiEmbedTypes:()=>rs,AxAIGoogleGeminiModel:()=>Cn,AxAIGoogleGeminiSafetyCategory:()=>Ar,AxAIGoogleGeminiSafetyThreshold:()=>xr,AxAIGrok:()=>Vt,AxAIGrokEmbedModels:()=>fs,AxAIGrokModel:()=>En,AxAIGroq:()=>Lt,AxAIGroqModel:()=>Rn,AxAIHuggingFace:()=>Gt,AxAIHuggingFaceModel:()=>Cr,AxAIMistral:()=>Ut,AxAIMistralEmbedModels:()=>ls,AxAIMistralModel:()=>wn,AxAIOllama:()=>Bt,AxAIOpenAI:()=>Pt,AxAIOpenAIBase:()=>pe,AxAIOpenAIEmbedModel:()=>Ot,AxAIOpenAIModel:()=>yn,AxAIOpenAIResponses:()=>qt,AxAIOpenAIResponsesBase:()=>Sn,AxAIOpenAIResponsesImpl:()=>jt,AxAIOpenAIResponsesModel:()=>Mt,AxAIOpenRouter:()=>zt,AxAIRefusalError:()=>ae,AxAIReka:()=>Ht,AxAIRekaModel:()=>kn,AxAIServiceAbortedError:()=>wt,AxAIServiceAuthenticationError:()=>it,AxAIServiceError:()=>Te,AxAIServiceNetworkError:()=>We,AxAIServiceResponseError:()=>tt,AxAIServiceStatusError:()=>ht,AxAIServiceStreamTerminatedError:()=>Be,AxAIServiceTimeoutError:()=>ft,AxAITogether:()=>Kt,AxAIWebLLM:()=>Wt,AxAIWebLLMModel:()=>Mn,AxAgent:()=>Yn,AxApacheTika:()=>ao,AxAssertionError:()=>Ve,AxBalancer:()=>pr,AxBaseAI:()=>de,AxBaseOptimizer:()=>Se,AxBootstrapFewShot:()=>rn,AxContentProcessingError:()=>je,AxDB:()=>$r,AxDBBase:()=>Fe,AxDBCloudflare:()=>Jt,AxDBManager:()=>Lr,AxDBMemory:()=>at,AxDBPinecone:()=>Qt,AxDBWeaviate:()=>Yt,AxDefaultCostTracker:()=>qn,AxDefaultResultReranker:()=>io,AxDockerSession:()=>Co,AxEmbeddingAdapter:()=>Ro,AxEvalUtil:()=>rl,AxFlow:()=>Jn,AxFlowDependencyAnalyzer:()=>on,AxFlowExecutionPlanner:()=>an,AxFlowSubContextImpl:()=>un,AxFlowTypedSubContextImpl:()=>Io,AxFluentFieldType:()=>ge,AxFunctionError:()=>Nn,AxFunctionProcessor:()=>$n,AxGEPA:()=>Ao,AxGEPAFlow:()=>xo,AxGen:()=>we,AxGenerateError:()=>Bn,AxHFDataLoader:()=>po,AxInstanceRegistry:()=>tn,AxLLMRequestTypeValues:()=>Bo,AxMCPClient:()=>wo,AxMCPHTTPSSETransport:()=>ko,AxMCPStreambleHTTPTransport:()=>vo,AxMediaNotSupportedError:()=>Pe,AxMemory:()=>Xt,AxMiPRO:()=>bo,AxMockAIService:()=>Sr,AxMultiServiceRouter:()=>vr,AxOptimizedProgramImpl:()=>Qe,AxProgram:()=>ut,AxPromptTemplate:()=>bt,AxProviderRouter:()=>Er,AxRateLimiterTokenUsage:()=>$t,AxSignature:()=>ce,AxSignatureBuilder:()=>Gn,AxSimpleClassifier:()=>co,AxSimpleClassifierClass:()=>lo,AxSpanKindValues:()=>jo,AxStopFunctionCallException:()=>yt,AxStringUtil:()=>so,AxTestPrompt:()=>uo,agent:()=>wl,ai:()=>sa,ax:()=>fe,axAIAnthropicDefaultConfig:()=>Qo,axAIAnthropicVertexDefaultConfig:()=>_i,axAIAzureOpenAIBestConfig:()=>Li,axAIAzureOpenAICreativeConfig:()=>Di,axAIAzureOpenAIDefaultConfig:()=>Xo,axAIAzureOpenAIFastConfig:()=>$i,axAICohereCreativeConfig:()=>qi,axAICohereDefaultConfig:()=>ts,axAIDeepSeekCodeConfig:()=>zi,axAIDeepSeekDefaultConfig:()=>ns,axAIGoogleGeminiDefaultConfig:()=>ss,axAIGoogleGeminiDefaultCreativeConfig:()=>Ki,axAIGrokBestConfig:()=>oa,axAIGrokDefaultConfig:()=>Nr,axAIHuggingFaceCreativeConfig:()=>Wi,axAIHuggingFaceDefaultConfig:()=>as,axAIMistralBestConfig:()=>Vi,axAIMistralDefaultConfig:()=>wr,axAIOllamaDefaultConfig:()=>cs,axAIOllamaDefaultCreativeConfig:()=>Ji,axAIOpenAIBestConfig:()=>lr,axAIOpenAICreativeConfig:()=>cr,axAIOpenAIDefaultConfig:()=>At,axAIOpenAIFastConfig:()=>ur,axAIOpenAIResponsesBestConfig:()=>Qi,axAIOpenAIResponsesCreativeConfig:()=>Yi,axAIOpenAIResponsesDefaultConfig:()=>vn,axAIOpenRouterDefaultConfig:()=>ps,axAIRekaBestConfig:()=>ea,axAIRekaCreativeConfig:()=>ta,axAIRekaDefaultConfig:()=>On,axAIRekaFastConfig:()=>na,axAITogetherDefaultConfig:()=>ms,axAIWebLLMCreativeConfig:()=>ra,axAIWebLLMDefaultConfig:()=>hs,axAnalyzeChatPromptRequirements:()=>Xi,axAnalyzeRequestRequirements:()=>xt,axBaseAIDefaultConfig:()=>X,axBaseAIDefaultCreativeConfig:()=>me,axCheckMetricsHealth:()=>ia,axCreateDefaultColorLogger:()=>Uo,axCreateDefaultOptimizerColorLogger:()=>Us,axCreateDefaultOptimizerTextLogger:()=>sl,axCreateDefaultTextLogger:()=>ri,axCreateFlowColorLogger:()=>Vn,axCreateFlowTextLogger:()=>dl,axDefaultFlowLogger:()=>ml,axDefaultMetricsConfig:()=>bs,axDefaultOptimizerLogger:()=>jn,axDefaultOptimizerMetricsConfig:()=>Bs,axGetCompatibilityReport:()=>Gi,axGetFormatCompatibility:()=>Bi,axGetMetricsConfig:()=>la,axGetOptimizerMetricsConfig:()=>al,axGetProvidersWithMediaSupport:()=>Ui,axGlobals:()=>Q,axModelInfoAnthropic:()=>An,axModelInfoCohere:()=>gr,axModelInfoDeepSeek:()=>hr,axModelInfoGoogleGemini:()=>yr,axModelInfoGrok:()=>_r,axModelInfoGroq:()=>Ir,axModelInfoHuggingFace:()=>Tr,axModelInfoMistral:()=>Rr,axModelInfoOpenAI:()=>Et,axModelInfoOpenAIResponses:()=>ar,axModelInfoReka:()=>Mr,axModelInfoTogether:()=>Pr,axModelInfoWebLLM:()=>Fr,axProcessContentForProvider:()=>Or,axRAG:()=>Sl,axScoreProvidersForRequest:()=>dr,axSelectOptimalProvider:()=>mr,axSpanAttributes:()=>j,axSpanEvents:()=>qe,axUpdateMetricsConfig:()=>aa,axUpdateOptimizerMetricsConfig:()=>il,axValidateChatRequestMessage:()=>St,axValidateChatResponseResult:()=>sr,axValidateProviderCapabilities:()=>Zo,f:()=>re,flow:()=>To,s:()=>ll});module.exports=Ll(pu);function Me({model:i,modelInfo:e,models:t}){let n=t?.find(l=>l.key===i),r=n&&"model"in n?n.model:i,o=e.find(l=>l.name===i);if(o)return o;let s=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===s);return a||null}var Lo=(()=>{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 xe(){return Lo.randomUUID()}async function Gl(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Lo.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var $o=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 Gl(this.data)}};function Ee(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new $o}function Js(){return Lo}var er=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
|
|
2
2
|
`).split(`
|
|
3
3
|
`);this.buffer=n.pop()||"";for(let r of n)r===""?this.processEvent(e):this.parseLine(r)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
|
|
4
4
|
`)?`
|
|
@@ -149,7 +149,7 @@ ${e}
|
|
|
149
149
|
`)}),r+=`${e}
|
|
150
150
|
`;break}default:r=JSON.stringify(n,null,2)}i(r)}};var j={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},qe={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},Bo=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Bo||{}),jo=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(jo||{});var qo=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()}},nr=class extends TransformStream{constructor(e,t){super(new qo(e,t))}};function rr(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 oi=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var si=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)},ii=(i,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:i})};function ai(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?rr(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var li=(i,e)=>{e({name:"FunctionResults",value:i})},zo=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},ci=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},ui=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},pi=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var di=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},mi=(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)},gi=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var Ho=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},or,hi=i=>{if(or)return or;if(i)return or=ql(i),or};var ql=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)"})}),fi=(i,e,t,n,r)=>{try{if(i.latencyHistogram){let o=Ho({operation:e,ai_service:n,...r?{model:r}:{}});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Ai=(i,e,t,n,r,o,s)=>{let a={operation:e,ai_service:o,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,a)},xi=(i,e,t,n)=>{try{if(i.errorCounter){let r=Ho({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},yi=(i,e,t,n,r)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},bi=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},hn=(i,e,t,n,r)=>{try{let o=Ho({ai_service:n,...r?{model:r}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,o),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},Ii=(i,e,t,n,r)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Ti=(i,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},Ko=(i,e,t,n,r)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Wo=(i,e,t,n,r)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Ci=(i,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},Vo=(i,e,t,n,r)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Ri=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},wi=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Si=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},vi=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},ki=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Oi=(i,e,t,n,r)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};function Mi(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function ze(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Mi(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Mi(e.item)}`),new Error(t.join(`
|
|
151
151
|
`))}function St(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 n=="string"&&n.trim()!=="",s=Array.isArray(r)&&r.length>0;if(!o&&!s&&ze("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:r},item:i}),n!==void 0&&typeof n!="string"&&ze("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&ze("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let a=0;a<r.length;a++){let l=r[a];if((!l||typeof l!="object")&&ze("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:i}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&ze("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:i}),(!("type"in l)||l.type!=="function")&&ze("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:i}),!("function"in l)||!l.function)ze("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:i});else{let c=l.function;(!("name"in c)||typeof c.name!="string"||c.name.trim()==="")&&ze("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:c?.name,item:i}),c.params!==void 0&&typeof c.params!="string"&&typeof c.params!="object"&&ze("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:c.params,item:i})}}if(i.name!==void 0){let a=i.name;(typeof a!="string"||a.trim()==="")&&ze("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,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"&&ze("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.thoughtBlock&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlock!==void 0){if(typeof r.thoughtBlock!="object"||r.thoughtBlock===null)throw new Error(`Chat response result thoughtBlock at index ${n} must be an object, received: ${e(r.thoughtBlock)}`);let o=r.thoughtBlock;if(typeof o.data!="string")throw new Error(`Chat response result thoughtBlock.data at index ${n} must be a string, received: ${e(o.data)}`);if(typeof o.encrypted!="boolean")throw new Error(`Chat response result thoughtBlock.encrypted at index ${n} must be a boolean, received: ${e(o.encrypted)}`);if(o.signature!==void 0&&typeof o.signature!="string")throw new Error(`Chat response result thoughtBlock.signature at index ${n} must be a string when provided, received: ${e(o.signature)}`)}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let 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 X=()=>structuredClone({temperature:0}),me=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),de=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??Q.tracer,this.meter=a.meter??Q.meter,this.modelInfo=o,this.models=c,this.id=xe();let u=this.getModel(s.model)??s.model,d=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:d},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&Hl(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=Q.logger??ni;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return hi(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??Q.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??Q.tracer,this.meter=e.meter??Q.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??Q.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.#e,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,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;fi(r,e,t,this.name,o),Ai(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;bi(r,e,this.name,o),t&&xi(r,e,this.name,o),yi(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:s}=e.tokens;n&&hn(t,"input",n,this.name,e.model),r&&hn(t,"output",r,this.name,e.model),o&&hn(t,"total",o,this.name,e.model),s&&hn(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let 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&&Ti(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Si(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;vi(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;Ii(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);Oi(r,l,c,this.name,o);let u=this.calculatePromptLength(e);Ri(r,u,this.name,o),Ci(r,s?.temperature,s?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&ki(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let d=this.calculateRequestSize(e);if(Ko(r,"chat",d,this.name,o),n&&!a){let p=n,m=this.calculateResponseSize(p);if(Wo(r,"chat",m,this.name,o),p.results)for(let g of p.results)g.functionCalls&&this.recordFunctionCallMetrics(g.functionCalls,this.lastUsedChatModel);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,p.modelUsage);h>0&&wi(r,h,this.name,o);let A=this.estimateCost(this.lastUsedChatModel,p.modelUsage);A>0&&Vo(r,"chat",A,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);Ko(n,"embed",o,this.name,r);let s=this.calculateResponseSize(t);Wo(n,"embed",s,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&Vo(n,"embed",a,this.name,r)}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)St(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:vt.SpanKind.SERVER,attributes:{[j.LLM_SYSTEM]:this.name,[j.LLM_OPERATION_NAME]:"chat",[j.LLM_REQUEST_MODEL]:n,[j.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[j.LLM_REQUEST_TEMPERATURE]:o.temperature,[j.LLM_REQUEST_TOP_P]:o.topP??"Not set",[j.LLM_REQUEST_TOP_K]:o.topK??"Not set",[j.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[j.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[j.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[j.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??vt.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;n.functions&&n.functions.length>0&&(a=n.functions.map(f=>this.cleanupFunctionSchema(f)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&oi(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,u=r?.functionCallMode??"auto",p=u==="prompt"||u==="auto"&&!c?{...l,chatPrompt:l.chatPrompt.map(f=>{if(f.role==="assistant"){let{content:x,name:b,cache:I}=f;return{role:"assistant",content:x,name:b,cache:I}}return f.role==="function"?{role:"user",content:f.result}:f}),functions:[]}:l,m=async()=>{let[f,x]=await this.aiImpl.createChatReq(p,r);return o?.isRecording()&&zl(n,o,this.excludeContentFromTrace),await Re({name:f.name,url:this.apiURL,localCall:f.localCall,headers:await this.buildHeaders(f.headers),stream:t.stream,timeout:this.timeout,debug:s,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},x)},h=r?.rateLimiter??this.rt,A=h?await h(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let f=this.aiImpl.createChatStreamResp.bind(this),x=T=>w=>{let y=f(w,T);if(y.sessionId=r?.sessionId,!y.modelUsage){let k=this.aiImpl.getTokenUsage();k&&(y.modelUsage={ai:this.name,model:e,tokens:k})}if(this.modelUsage=y.modelUsage,this.recordTokenUsage(y.modelUsage),o?.isRecording()&&Ei(y,o,this.excludeContentFromTrace),s)for(let k of y.results)ii(k,k.index,r?.logger??this.logger);return y},b=async T=>{o?.isRecording()&&o.end(),s&&ai(T,r?.logger??this.logger)};if(typeof window<"u"){let T=A,w={},y=[],k=r?.abortSignal??this.abortSignal;return new ReadableStream({start:E=>{let M=T.getReader(),R=()=>{try{M.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{E.error(new DOMException("Aborted","AbortError"))}catch{E.error(new Error("Aborted"))}};if(k){if(k.aborted){R();return}k.addEventListener("abort",R,{once:!0})}async function P(){try{for(;;){let{done:C,value:v}=await M.read();if(C){b&&await b(y),E.close();break}let O=x(w)(v);O&&(y.push(O),E.enqueue(O))}}catch(C){if(E.error(C),o?.isRecording())try{o.end()}catch{}}finally{if(M.releaseLock(),k)try{k.removeEventListener("abort",R)}catch{}}}P()}})}return A.pipeThrough(new nr(x({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let g=this.aiImpl.createChatResp(A);if(g.sessionId=r?.sessionId,!g.modelUsage){let f=this.aiImpl.getTokenUsage();f&&(g.modelUsage={ai:this.name,model:e,tokens:f})}return g.modelUsage&&(this.modelUsage=g.modelUsage,this.recordTokenUsage(g.modelUsage)),o?.isRecording()&&(Ei(g,o,this.excludeContentFromTrace),o.end()),s&&si(g,r?.logger??this.logger),g}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:vt.SpanKind.SERVER,attributes:{[j.LLM_SYSTEM]:this.name,[j.LLM_OPERATION_NAME]:"embeddings",[j.LLM_REQUEST_MODEL]:n}},t?.traceContext??vt.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={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&di(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[p,m]=await o(a);return await Re({name:p.name,url:this.apiURL,localCall:p.localCall,headers:await this.buildHeaders(p.headers),debug:s,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},c=n?.rateLimiter??this.rt,u=c?await c(l,{modelUsage:this.embedModelUsage}):await l(),d=this.aiImpl.createEmbedResp?.(u);if(d.sessionId=n?.sessionId,!d.modelUsage){let p=this.aiImpl.getTokenUsage();p&&(d.modelUsage={ai:this.name,model:e,tokens:p})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(qe.GEN_AI_USAGE,{[j.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[j.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[j.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&mi(d.embeddings,n?.logger??this.logger),r?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function zl(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(qe.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(qe.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(qe.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(qe.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
|
|
152
|
-
`)),e.addEvent(qe.GEN_AI_USER_MESSAGE,r)}function Ei(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[j.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(qe.GEN_AI_USAGE,{[j.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[j.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[j.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(qe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Pi(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 Hl(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 fn=(m=>(m.Claude41Opus="claude-opus-4-1-20250805",m.Claude4Opus="claude-opus-4-20250514",m.Claude4Sonnet="claude-sonnet-4-20250514",m.Claude45Sonnet="claude-sonnet-4-5-20250929",m.Claude45Haiku="claude-haiku-4-5",m.Claude37Sonnet="claude-3-7-sonnet-latest",m.Claude35Sonnet="claude-3-5-sonnet-latest",m.Claude35Haiku="claude-3-5-haiku-latest",m.Claude3Opus="claude-3-opus-latest",m.Claude3Sonnet="claude-3-sonnet-20240229",m.Claude3Haiku="claude-3-haiku-20240307",m.Claude21="claude-2.1",m.ClaudeInstant12="claude-instant-1.2",m))(fn||{}),ir=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(ir||{});var An=[{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var xn=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,xn(n)]))),e.items&&(e.items=xn(e.items)),e},Qo=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...X()}),_i=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...X()}),Jo=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.filter(y=>y.role==="system").map(y=>({type:"text",text:y.content,...y.cache?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),c=e.functions?.map(y=>{let k={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},E=y.parameters?xn(y.parameters):void 0;return E===void 0||E&&typeof E=="object"&&Object.keys(E).length===0?E={...k}:E&&typeof E=="object"&&E.type==="object"&&(!("properties"in E)||!E.properties||Object.keys(E.properties).length===0)&&(E={...E,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:y.name,description:y.description,input_schema:E}}),d=(this.config.tools??[]).map(y=>y&&typeof y=="object"&&"type"in y?y:{name:y.name,description:y.description,input_schema:y.input_schema?xn(y.input_schema):void 0,...y.cache_control?{cache_control:y.cache_control}:{}}),p=[...c??[],...d];this.isVertex&&p.length>0&&(p=p.filter(y=>!(y&&typeof y=="object"&&"type"in y))),p.length===0&&(p=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,g=e.modelConfig?.topP,f=e.modelConfig?.topK??this.config.topK,x=e.modelConfig?.n??this.config.n;if(x&&x>1)throw new Error("Anthropic does not support sampling (n > 1)");let b;if(this.config.thinking?.budget_tokens&&(b=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:y?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let y=this.config.thinkingTokenBudgetLevels}let I=Kl(l,!!b);I.some(y=>y.role==="assistant"&&Array.isArray(y.content)&&y.content.length>0&&y.content[0]?.type==="tool_use")&&(b=void 0);let T;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let y=e.responseFormat.schema.schema||e.responseFormat.schema;T={type:"json_schema",schema:xn(y)},this.usedStructuredOutput=!0}let w={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...h&&h.length>0?{stop_sequences:h}:{},...A!==void 0&&!b?{temperature:A}:{},...g!==void 0&&(!b||g>=.95)?{top_p:g}:{},...f&&!b?{top_k:f}:{},...s,...p?{tools:p}:{},...r?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},...T?{output_format:T}:{},messages:I};return[o,w]};createChatResp=e=>{if(e.type==="error")throw new ae(e.error.message,void 0,void 0);let t=Fi(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",s=!1,a,l=[],c=[];for(let p of e.content)switch(p.type){case"text":if(r+=p.text??"",Array.isArray(p.citations))for(let m of p.citations)m?.url&&c.push({url:String(m.url),title:typeof m.title=="string"?m.title:void 0,snippet:typeof m.cited_text=="string"?m.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=p.thinking??p.data??""),p.type==="redacted_thinking"&&(s=!0),typeof p.signature=="string"&&(a=p.signature);break;case"tool_use":l.push({id:p.id,type:"function",function:{name:p.name,params:p.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),o&&(u.thought=o,u.thoughtBlock={data:o,encrypted:s,...a?{signature:a}:{}}),l.length>0&&(u.functionCalls=l),c.length>0&&(u.citations=c);let d=[u];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:d,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new ae(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let 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,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlock:{data:"",encrypted:!1,signature:o.signature}}]};if(o.type==="input_json_delta"){let 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:Fi(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},kt=class i extends de{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}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13","x-api-key":typeof e=="function"?await e():e})}let u={...Qo(),...r},d=new Jo(u,a),p=h=>{let A=Me({model:h,modelInfo:An,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(h=>{let A=h,g=A?.config;if(!g)return h;let f={};g.maxTokens!==void 0&&(f.maxTokens=g.maxTokens),g.temperature!==void 0&&(f.temperature=g.temperature),g.topP!==void 0&&(f.topP=g.topP),g.topK!==void 0&&(f.topK=g.topK),g.presencePenalty!==void 0&&(f.presencePenalty=g.presencePenalty),g.frequencyPenalty!==void 0&&(f.frequencyPenalty=g.frequencyPenalty),g.stopSequences!==void 0&&(f.stopSequences=g.stopSequences),g.endSequences!==void 0&&(f.endSequences=g.endSequences),g.stream!==void 0&&(f.stream=g.stream),g.n!==void 0&&(f.n=g.n);let x={...A};Object.keys(f).length>0&&(x.modelConfig={...A.modelConfig??{},...f});let b=g.thinking?.thinkingTokenBudget;if(typeof b=="number"){let I=u.thinkingTokenBudgetLevels,S=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],T="minimal",w=Number.POSITIVE_INFINITY;for(let[y,k]of S){let E=Math.abs(b-k);E<w&&(w=E,T=y)}x.thinkingTokenBudget=T}return g.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!g.thinking.includeThoughts),x});super(d,{name:"Anthropic",apiURL:l,headers:c,modelInfo:An,defaults:{model:u.model},options:o,supportFor:p,models:m??s})}};function Kl(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}:{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.thoughtBlock;return a&&typeof a.data=="string"&&a.data.length>0&&(a.encrypted?s.push(a.signature?{type:"redacted_thinking",data:a.data,signature:a.signature}:{type:"redacted_thinking",data:a.data}):s.push(a.signature?{type:"thinking",thinking:a.data,signature:a.signature}:{type:"thinking",thinking:a.data})),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])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Wl(t);return Vl(n)}function Wl(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 Vl(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Fi(i){if(i)switch(i){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var yn=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT41Nano="gpt-4.1-nano",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1="o1",T.O1Mini="o1-mini",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(yn||{}),Ot=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Ot||{});var Mt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT41Nano="gpt-4.1-nano",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",y.O1Pro="o1-pro",y.O1="o1",y.O1Mini="o1-mini",y.O3Pro="o3-pro",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(Mt||{});var Et=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],ar=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Jl=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},At=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...X()}),lr=()=>structuredClone({...At(),model:"gpt-5"}),cr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...me()}),ur=()=>({...At(),model:"gpt-5-nano"}),Yo=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=Ql(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=Jl(n),p={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...d?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(p.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(p.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":p.reasoning_effort=void 0;break;case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":p.reasoning_effort="high";break;case"high":p.reasoning_effort="high";break;case"highest":p.reasoning_effort="high";break}if(!p.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":case"high":case"highest":p.reasoning_effort="high";break}return this.chatReqUpdater&&(p=this.chatReqUpdater(p)),[r,p]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new ae(a.message.refusal,e.model,e.id);let l=Ni(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:d,name:p}})=>({id:u,type:"function",function:{name:p,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:d,tool_calls:p,reasoning_content:m,annotations:h},finish_reason:A})=>{if(d)throw new ae(d,void 0,n);let g=Ni(A),f=p?.map(({id:x,index:b,function:{name:I,arguments:S}})=>{typeof x=="string"&&typeof b=="number"&&!s.indexIdMap[b]&&(s.indexIdMap[b]=x);let T=s.indexIdMap[b];return T?{id:T,type:"function",function:{name:I,params:S}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:f,finishReason:g,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Ni=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ql(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 pe=class extends de{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 Yo(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})}},Pt=class extends pe{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=[...Et,...s??[]];let a=c=>{let u=Me({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,d=u?.config;if(!d)return c;let p={};d.maxTokens!==void 0&&(p.maxTokens=d.maxTokens),d.temperature!==void 0&&(p.temperature=d.temperature),d.topP!==void 0&&(p.topP=d.topP),d.presencePenalty!==void 0&&(p.presencePenalty=d.presencePenalty),d.frequencyPenalty!==void 0&&(p.frequencyPenalty=d.frequencyPenalty);let m=d.stopSequences??d.stop;m!==void 0&&(p.stopSequences=m),d.n!==void 0&&(p.n=d.n),d.stream!==void 0&&(p.stream=d.stream);let h={...u};Object.keys(p).length>0&&(h.modelConfig={...u.modelConfig??{},...p});let A=d?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let g=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],f="minimal",x=Number.POSITIVE_INFINITY;for(let[b,I]of g){let S=Math.abs(A-I);S<x&&(x=S,f=b)}h.thinkingTokenBudget=f}return d?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!d.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...At(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Xo=At,Di=cr,$i=ur,Li=lr,Ft=class extends pe{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={...Xo(),...o};l=[...Et,...l??[]];let u=p=>{let m=Me({model:p,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:u});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var pr=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.");Yl(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(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,r=Date.now()-n,o=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return r>=o}handleFailure(e){let n=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:n,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${n}/${this.maxRetries})`,e),n>=this.maxRetries){let r=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`,e),r}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te))throw n;switch(n.constructor){case it:throw n;case ht:break;case We:break;case tt:break;case Be:break;case ft:break;default:throw n}if(!this.handleFailure(n))throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Yl(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 xt(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 d of u.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),c+=85;break;case"audio":t=!0,d.cache&&(a=!0),c+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),c+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":r=!0,d.cache&&(a=!0),c+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),c+=Math.ceil(d.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return 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 Zo(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 dr(i,e){return i.map(t=>{let n=t.getFeatures(),r=Zo(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 mr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=xt(i),r=dr(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 Gi(i,e){let t=xt(i),n=dr(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 Ui(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Bi(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 bn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(bn||{}),In=(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))(In||{});var gr=[{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 ts=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...X()}),qi=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...me()}),es=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,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=Xl(r),a=e.functions?.map(d=>{let p={};if(d.parameters?.properties)for(let[m,h]of Object.entries(d.parameters.properties))p[m]={description:h.description,type:h.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:p}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let p=a?.find(m=>m.name===d.functionId);if(!p)throw new Error("Function not found");return{call:{name:p.name,parameters:p.parameter_definitions},outputs:[{result:d.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history: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}}},_t=class extends de{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...ts(),...t},s=new es(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.topK!==void 0&&(d.topK=u.topK),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(d.stopSequences=u.stopSequences),u.endSequences!==void 0&&(d.endSequences=u.endSequences),u.stream!==void 0&&(d.stream=u.stream),u.n!==void 0&&(d.n=u.n);let p={...c};return Object.keys(d).length>0&&(p.modelConfig={...c.modelConfig??{},...d}),p});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:gr,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 Xl(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=ji(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=ji(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 ji(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 Tn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Tn||{});var hr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var ns=()=>structuredClone({model:"deepseek-chat",...X()}),zi=()=>structuredClone({model:"deepseek-coder",...me()}),Nt=class extends pe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...ns(),...t};o=[...hr,...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 Cn=(f=>(f.Gemini3ProPreview="gemini-3-pro-preview",f.Gemini3ProImagePreview="gemini-3-pro-image-preview",f.Gemini25Pro="gemini-2.5-pro",f.Gemini25Flash="gemini-2.5-flash",f.Gemini25FlashLite="gemini-2.5-flash-lite",f.Gemini20Flash="gemini-2.0-flash",f.Gemini20FlashLite="gemini-2.0-flash-lite",f.Gemini20ProExp="gemini-2.0-pro-exp-02-05",f.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",f.Gemini1Pro="gemini-1.0-pro",f.Gemini15Flash="gemini-1.5-flash",f.Gemini15Flash002="gemini-1.5-flash-002",f.Gemini15Flash8B="gemini-1.5-flash-8b",f.Gemini15Pro="gemini-1.5-pro",f.GeminiFlashLatest="gemini-flash-latest",f.GeminiFlashLiteLatest="gemini-flash-lite-latest",f.GeminiProLatest="gemini-pro-latest",f))(Cn||{}),fr=(r=>(r.GeminiEmbedding="gemini-embedding-exp",r.TextEmbeddingLarge="text-embedding-large-exp-03-07",r.TextEmbedding004="text-embedding-004",r.TextEmbedding005="text-embedding-005",r))(fr||{}),Ar=(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))(Ar||{}),xr=(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))(xr||{}),rs=(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))(rs||{});var yr=[{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var br=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,br(n)]))),e.items&&(e.items=br(e.items)),e},Hi=[{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"}],ss=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Hi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...X()}),Ki=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Hi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...me()}),os=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let g=r?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${g}key=${f}`}let s=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((b,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:g.content}]};case"assistant":{let x=[],b=g.thoughtBlock,I=!1;if(b?.data&&(x.push({thought:!0,text:b.data,...b.signature?{thoughtSignature:b.signature}:{}}),b.signature&&(I=!0)),g.functionCalls){let S=g.functionCalls.map((T,w)=>{let y;if(typeof T.function.params=="string"){let E=T.function.params;if(E.trim().length===0)y={};else try{y=JSON.parse(E)}catch{throw new Error(`Failed to parse function params JSON: ${E}`)}}else y=T.function.params;let k={functionCall:{name:T.function.name,args:y}};return w===0&&!I&&b&&b.signature&&(k.thoughtSignature=b.signature,I=!0),k});x.push(...S)}if(g.content&&x.push({text:g.content}),x.length===0)throw new Error("Assistant content is empty");return{role:"model",parts:x}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),c=[];if(e.functions&&e.functions.length>0){let g=e.functions.map(f=>{let x={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=f.parameters?br(f.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...x}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...f,parameters:b}});c.push({function_declarations:g})}if(this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.googleMaps){let g=this.options.googleMaps,f=g?.enableWidget!==void 0?{enableWidget:g.enableWidget}:{};c.push({google_maps:f})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,d=Array.isArray(c)?c.some(g=>g&&Array.isArray(g.function_declarations)&&g.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let g=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...g}}else d&&(u={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(u={...u??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let p={};if(this.config.thinking?.includeThoughts&&(p.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(p.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(p.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let g=this.config.thinkingTokenBudgetLevels,f=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":p.thinkingBudget=0,p.includeThoughts=!1,delete p.thinkingLevel;break;case"minimal":p.thinkingBudget=g?.minimal??200,f&&(p.thinkingLevel="low");break;case"low":p.thinkingBudget=g?.low??800,f&&(p.thinkingLevel="low");break;case"medium":p.thinkingBudget=g?.medium??5e3,f&&(p.thinkingLevel="high");break;case"high":p.thinkingBudget=g?.high??1e4,f&&(p.thinkingLevel="high");break;case"highest":p.thinkingBudget=g?.highest??24500,f&&(p.thinkingLevel="high");break}}p.thinkingLevel&&delete p.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(p.includeThoughts=t.showThoughts);let m={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(p).length>0?{thinkingConfig:p}:{}};if(e.responseFormat){if(m.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let g=e.responseFormat.schema.schema||e.responseFormat.schema;m.responseSchema=br(g)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(m.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new ae("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new ae("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new ae("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new ae("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new ae("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new ae("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new ae("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new ae("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new ae("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){"thought"in c&&c.thought||c.thought===!0?(s.thought=c.text,s.thoughtBlock={data:c.text,encrypted:!1,...c.thoughtSignature?{signature:c.thoughtSignature}:{}}):s.content=c.text;continue}"functionCall"in c&&(c.thoughtSignature&&(s.thoughtBlock?s.thoughtBlock.signature=c.thoughtSignature:s.thoughtBlock={data:"",encrypted:!1,signature:c.thoughtSignature}),s.functionCalls=[...s.functionCalls??[],{id:xe(),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});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}}},Dt=class i extends de{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,d;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let g;r?g="endpoints":g="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let p={...ss(),...o},m=new os(p,c,r,e,s);l=[...yr,...l??[]];let h=g=>{let f=Me({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},A=a?.map(g=>{let f=g,x=f?.config;if(!x)return g;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let I={...f};Object.keys(b).length>0&&(I.modelConfig={...f.modelConfig??{},...b});let S=x.thinking?.thinkingTokenBudget;if(typeof S=="number"){let T=p.thinkingTokenBudgetLevels,w=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],y="minimal",k=Number.POSITIVE_INFINITY;for(let[E,M]of w){let R=Math.abs(S-M);R<k&&(k=R,y=E)}I.thinkingTokenBudget=y}return x.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!x.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:p.model,embedModel:p.embedModel},options:s,supportFor:h,models:A??a})}};var Zl=new Ce,$t=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(Zl.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 Rn=(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))(Rn||{});var Ir=[{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 ec=()=>structuredClone({model:"llama-3.3-70b-versatile",...X()}),Lt=class extends pe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...ec(),...t},a={...n,streamingUsage:!1};o=[...Ir,...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 $t(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 Tr=[];var Cr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Cr||{});var as=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...X()}),Wi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...me()}),is=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
|
|
152
|
+
`)),e.addEvent(qe.GEN_AI_USER_MESSAGE,r)}function Ei(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[j.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(qe.GEN_AI_USAGE,{[j.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[j.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[j.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(qe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Pi(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 Hl(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 fn=(m=>(m.Claude41Opus="claude-opus-4-1-20250805",m.Claude4Opus="claude-opus-4-20250514",m.Claude4Sonnet="claude-sonnet-4-20250514",m.Claude45Sonnet="claude-sonnet-4-5-20250929",m.Claude45Haiku="claude-haiku-4-5",m.Claude37Sonnet="claude-3-7-sonnet-latest",m.Claude35Sonnet="claude-3-5-sonnet-latest",m.Claude35Haiku="claude-3-5-haiku-latest",m.Claude3Opus="claude-3-opus-latest",m.Claude3Sonnet="claude-3-sonnet-20240229",m.Claude3Haiku="claude-3-haiku-20240307",m.Claude21="claude-2.1",m.ClaudeInstant12="claude-instant-1.2",m))(fn||{}),ir=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(ir||{});var An=[{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var xn=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,xn(n)]))),e.items&&(e.items=xn(e.items)),e},Qo=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...X()}),_i=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...X()}),Jo=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.filter(y=>y.role==="system").map(y=>({type:"text",text:y.content,...y.cache?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(y=>y.role!=="system"),c=e.functions?.map(y=>{let k={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},E=y.parameters?xn(y.parameters):void 0;return E===void 0||E&&typeof E=="object"&&Object.keys(E).length===0?E={...k}:E&&typeof E=="object"&&E.type==="object"&&(!("properties"in E)||!E.properties||Object.keys(E.properties).length===0)&&(E={...E,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:y.name,description:y.description,input_schema:E}}),d=(this.config.tools??[]).map(y=>y&&typeof y=="object"&&"type"in y?y:{name:y.name,description:y.description,input_schema:y.input_schema?xn(y.input_schema):void 0,...y.cache_control?{cache_control:y.cache_control}:{}}),p=[...c??[],...d];this.isVertex&&p.length>0&&(p=p.filter(y=>!(y&&typeof y=="object"&&"type"in y))),p.length===0&&(p=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,g=e.modelConfig?.topP,f=e.modelConfig?.topK??this.config.topK,x=e.modelConfig?.n??this.config.n;if(x&&x>1)throw new Error("Anthropic does not support sampling (n > 1)");let b;if(this.config.thinking?.budget_tokens&&(b=this.config.thinking),t?.thinkingTokenBudget){let y=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":b=void 0;break;case"minimal":b={type:"enabled",budget_tokens:y?.minimal??1024};break;case"low":b={type:"enabled",budget_tokens:y?.low??5e3};break;case"medium":b={type:"enabled",budget_tokens:y?.medium??1e4};break;case"high":b={type:"enabled",budget_tokens:y?.high??2e4};break;case"highest":b={type:"enabled",budget_tokens:y?.highest??32e3};break}}if(!b&&t?.thinkingTokenBudget===void 0){let y=this.config.thinkingTokenBudgetLevels}let I=Kl(l,!!b);I.some(y=>y.role==="assistant"&&Array.isArray(y.content)&&y.content.length>0&&y.content[0]?.type==="tool_use")&&(b=void 0);let T;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let y=e.responseFormat.schema.schema||e.responseFormat.schema;T={type:"json_schema",schema:xn(y)},this.usedStructuredOutput=!0}let w={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...h&&h.length>0?{stop_sequences:h}:{},...A!==void 0&&!b?{temperature:A}:{},...g!==void 0&&(!b||g>=.95)?{top_p:g}:{},...f&&!b?{top_k:f}:{},...s,...p?{tools:p}:{},...r?{stream:!0}:{},...a?{system:a}:{},...b?{thinking:b}:{},...T?{output_format:T}:{},messages:I};return[o,w]};createChatResp=e=>{if(e.type==="error")throw new ae(e.error.message,void 0,void 0);let t=Fi(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",s=!1,a,l=[],c=[];for(let p of e.content)switch(p.type){case"text":if(r+=p.text??"",Array.isArray(p.citations))for(let m of p.citations)m?.url&&c.push({url:String(m.url),title:typeof m.title=="string"?m.title:void 0,snippet:typeof m.cited_text=="string"?m.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=p.thinking??p.data??""),p.type==="redacted_thinking"&&(s=!0),typeof p.signature=="string"&&(a=p.signature);break;case"tool_use":l.push({id:p.id,type:"function",function:{name:p.name,params:p.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),o&&(u.thought=o,u.thoughtBlock={data:o,encrypted:s,...a?{signature:a}:{}}),l.length>0&&(u.functionCalls=l),c.length>0&&(u.citations=c);let d=[u];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:d,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new ae(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let 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,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlock:{data:"",encrypted:!1,signature:o.signature}}]};if(o.type==="input_json_delta"){let 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:Fi(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},kt=class i extends de{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}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13","x-api-key":typeof e=="function"?await e():e})}let u={...Qo(),...r},d=new Jo(u,a),p=h=>{let A=Me({model:h,modelInfo:An,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(h=>{let A=h,g=A?.config;if(!g)return h;let f={};g.maxTokens!==void 0&&(f.maxTokens=g.maxTokens),g.temperature!==void 0&&(f.temperature=g.temperature),g.topP!==void 0&&(f.topP=g.topP),g.topK!==void 0&&(f.topK=g.topK),g.presencePenalty!==void 0&&(f.presencePenalty=g.presencePenalty),g.frequencyPenalty!==void 0&&(f.frequencyPenalty=g.frequencyPenalty),g.stopSequences!==void 0&&(f.stopSequences=g.stopSequences),g.endSequences!==void 0&&(f.endSequences=g.endSequences),g.stream!==void 0&&(f.stream=g.stream),g.n!==void 0&&(f.n=g.n);let x={...A};Object.keys(f).length>0&&(x.modelConfig={...A.modelConfig??{},...f});let b=g.thinking?.thinkingTokenBudget;if(typeof b=="number"){let I=u.thinkingTokenBudgetLevels,S=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],T="minimal",w=Number.POSITIVE_INFINITY;for(let[y,k]of S){let E=Math.abs(b-k);E<w&&(w=E,T=y)}x.thinkingTokenBudget=T}return g.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!g.thinking.includeThoughts),x});super(d,{name:"Anthropic",apiURL:l,headers:c,modelInfo:An,defaults:{model:u.model},options:o,supportFor:p,models:m??s})}};function Kl(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}:{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.thoughtBlock;return a&&typeof a.data=="string"&&a.data.length>0&&(a.encrypted?s.push(a.signature?{type:"redacted_thinking",data:a.data,signature:a.signature}:{type:"redacted_thinking",data:a.data}):s.push(a.signature?{type:"thinking",thinking:a.data,signature:a.signature}:{type:"thinking",thinking:a.data})),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])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Wl(t);return Vl(n)}function Wl(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 Vl(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Fi(i){if(i)switch(i){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var yn=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT41Nano="gpt-4.1-nano",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1="o1",T.O1Mini="o1-mini",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(yn||{}),Ot=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Ot||{});var Mt=(y=>(y.GPT4="gpt-4",y.GPT41="gpt-4.1",y.GPT41Mini="gpt-4.1-mini",y.GPT41Nano="gpt-4.1-nano",y.GPT4O="gpt-4o",y.GPT4OMini="gpt-4o-mini",y.GPT4ChatGPT4O="chatgpt-4o-latest",y.GPT4Turbo="gpt-4-turbo",y.GPT35Turbo="gpt-3.5-turbo",y.GPT35TurboInstruct="gpt-3.5-turbo-instruct",y.GPT35TextDavinci002="text-davinci-002",y.GPT3TextBabbage002="text-babbage-002",y.GPT3TextAda001="text-ada-001",y.GPT5="gpt-5",y.GPT5Nano="gpt-5-nano",y.GPT5Mini="gpt-5-mini",y.GPT5Chat="gpt-5-chat",y.O1Pro="o1-pro",y.O1="o1",y.O1Mini="o1-mini",y.O3Pro="o3-pro",y.O3="o3",y.O3Mini="o3-mini",y.O4Mini="o4-mini",y))(Mt||{});var Et=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],ar=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Jl=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},At=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...X()}),lr=()=>structuredClone({...At(),model:"gpt-5"}),cr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...me()}),ur=()=>({...At(),model:"gpt-5-nano"}),Yo=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=Ql(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,d=Jl(n),p={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...d?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...u?{store:u}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(p.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(p.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":p.reasoning_effort=void 0;break;case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":p.reasoning_effort="high";break;case"high":p.reasoning_effort="high";break;case"highest":p.reasoning_effort="high";break}if(!p.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":p.reasoning_effort="minimal";break;case"low":p.reasoning_effort="medium";break;case"medium":case"high":case"highest":p.reasoning_effort="high";break}return this.chatReqUpdater&&(p=this.chatReqUpdater(p)),[r,p]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new ae(a.message.refusal,e.model,e.id);let l=Ni(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:d,name:p}})=>({id:u,type:"function",function:{name:p,params:d}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:u,refusal:d,tool_calls:p,reasoning_content:m,annotations:h},finish_reason:A})=>{if(d)throw new ae(d,void 0,n);let g=Ni(A),f=p?.map(({id:x,index:b,function:{name:I,arguments:S}})=>{typeof x=="string"&&typeof b=="number"&&!s.indexIdMap[b]&&(s.indexIdMap[b]=x);let T=s.indexIdMap[b];return T?{id:T,type:"function",function:{name:I,params:S}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:f,finishReason:g,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Ni=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ql(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 pe=class extends de{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 Yo(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})}},Pt=class extends pe{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=[...Et,...s??[]];let a=c=>{let u=Me({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let u=c,d=u?.config;if(!d)return c;let p={};d.maxTokens!==void 0&&(p.maxTokens=d.maxTokens),d.temperature!==void 0&&(p.temperature=d.temperature),d.topP!==void 0&&(p.topP=d.topP),d.presencePenalty!==void 0&&(p.presencePenalty=d.presencePenalty),d.frequencyPenalty!==void 0&&(p.frequencyPenalty=d.frequencyPenalty);let m=d.stopSequences??d.stop;m!==void 0&&(p.stopSequences=m),d.n!==void 0&&(p.n=d.n),d.stream!==void 0&&(p.stream=d.stream);let h={...u};Object.keys(p).length>0&&(h.modelConfig={...u.modelConfig??{},...p});let A=d?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let g=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],f="minimal",x=Number.POSITIVE_INFINITY;for(let[b,I]of g){let S=Math.abs(A-I);S<x&&(x=S,f=b)}h.thinkingTokenBudget=f}return d?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!d.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...At(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Xo=At,Di=cr,$i=ur,Li=lr,Ft=class extends pe{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={...Xo(),...o};l=[...Et,...l??[]];let u=p=>{let m=Me({model:p,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:u});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var pr=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.");Yl(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(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,r=Date.now()-n,o=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return r>=o}handleFailure(e){let n=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:n,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${n}/${this.maxRetries})`,e),n>=this.maxRetries){let r=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`,e),r}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te))throw n;switch(n.constructor){case it:throw n;case ht:break;case We:break;case tt:break;case Be:break;case ft:break;default:throw n}if(!this.handleFailure(n))throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Yl(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 xt(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 d of u.content)switch(l.add(d.type),d.type){case"image":e=!0,d.cache&&(a=!0),c+=85;break;case"audio":t=!0,d.cache&&(a=!0),c+=d.duration||60;break;case"file":n=!0,d.cache&&(a=!0),c+=Math.ceil((d.extractedText?.length||1e3)/4);break;case"url":r=!0,d.cache&&(a=!0),c+=Math.ceil((d.cachedContent?.length||2e3)/4);break;case"text":d.cache&&(a=!0),c+=Math.ceil(d.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return 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 Zo(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 dr(i,e){return i.map(t=>{let n=t.getFeatures(),r=Zo(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 mr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=xt(i),r=dr(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 Gi(i,e){let t=xt(i),n=dr(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 Ui(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Bi(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 bn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(bn||{}),In=(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))(In||{});var gr=[{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 ts=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...X()}),qi=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...me()}),es=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,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=Xl(r),a=e.functions?.map(d=>{let p={};if(d.parameters?.properties)for(let[m,h]of Object.entries(d.parameters.properties))p[m]={description:h.description,type:h.type,required:d.parameters.required?.includes(m)??!1};return{name:d.name,description:d.description,parameter_definitions:p}}),l=e.chatPrompt.filter(d=>d.role==="function").map(d=>{let p=a?.find(m=>m.name===d.functionId);if(!p)throw new Error("Function not found");return{call:{name:p.name,parameters:p.parameter_definitions},outputs:[{result:d.result??""}]}}),c={name:"/chat"},u={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history: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}}},_t=class extends de{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...ts(),...t},s=new es(o),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.topK!==void 0&&(d.topK=u.topK),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(d.stopSequences=u.stopSequences),u.endSequences!==void 0&&(d.endSequences=u.endSequences),u.stream!==void 0&&(d.stream=u.stream),u.n!==void 0&&(d.n=u.n);let p={...c};return Object.keys(d).length>0&&(p.modelConfig={...c.modelConfig??{},...d}),p});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:gr,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 Xl(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=ji(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=ji(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 ji(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 Tn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Tn||{});var hr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var ns=()=>structuredClone({model:"deepseek-chat",...X()}),zi=()=>structuredClone({model:"deepseek-coder",...me()}),Nt=class extends pe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...ns(),...t};o=[...hr,...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 Cn=(f=>(f.Gemini3ProPreview="gemini-3-pro-preview",f.Gemini3ProImagePreview="gemini-3-pro-image-preview",f.Gemini25Pro="gemini-2.5-pro",f.Gemini25Flash="gemini-2.5-flash",f.Gemini25FlashLite="gemini-2.5-flash-lite",f.Gemini20Flash="gemini-2.0-flash",f.Gemini20FlashLite="gemini-2.0-flash-lite",f.Gemini20ProExp="gemini-2.0-pro-exp-02-05",f.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",f.Gemini1Pro="gemini-1.0-pro",f.Gemini15Flash="gemini-1.5-flash",f.Gemini15Flash002="gemini-1.5-flash-002",f.Gemini15Flash8B="gemini-1.5-flash-8b",f.Gemini15Pro="gemini-1.5-pro",f.GeminiFlashLatest="gemini-flash-latest",f.GeminiFlashLiteLatest="gemini-flash-lite-latest",f.GeminiProLatest="gemini-pro-latest",f))(Cn||{}),fr=(r=>(r.GeminiEmbedding="gemini-embedding-exp",r.TextEmbeddingLarge="text-embedding-large-exp-03-07",r.TextEmbedding004="text-embedding-004",r.TextEmbedding005="text-embedding-005",r))(fr||{}),Ar=(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))(Ar||{}),xr=(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))(xr||{}),rs=(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))(rs||{});var yr=[{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var br=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,br(n)]))),e.items&&(e.items=br(e.items)),e},Hi=[{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"}],ss=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Hi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...X()}),Ki=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Hi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...me()}),os=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let g=r?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${g}key=${f}`}let s=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((b,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:g.content}]};case"assistant":{let x=[],b=g.thoughtBlock,I=g.functionCalls&&g.functionCalls.length>0;if(b?.data&&x.push({thought:!0,text:b.data,...b.signature&&!I?{thought_signature:b.signature}:{}}),g.functionCalls){let S=g.functionCalls.map((T,w)=>{let y;if(typeof T.function.params=="string"){let E=T.function.params;if(E.trim().length===0)y={};else try{y=JSON.parse(E)}catch{throw new Error(`Failed to parse function params JSON: ${E}`)}}else y=T.function.params;let k={functionCall:{name:T.function.name,args:y}};return b?.signature&&w===0&&(k.thought_signature=b.signature),k});x.push(...S)}if(g.content&&x.push({text:g.content}),x.length===0)throw new Error("Assistant content is empty");return{role:"model",parts:x}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),c=[];if(e.functions&&e.functions.length>0){let g=e.functions.map(f=>{let x={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=f.parameters?br(f.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...x}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...f,parameters:b}});c.push({function_declarations:g})}if(this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.googleMaps){let g=this.options.googleMaps,f=g?.enableWidget!==void 0?{enableWidget:g.enableWidget}:{};c.push({google_maps:f})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let u,d=Array.isArray(c)?c.some(g=>g&&Array.isArray(g.function_declarations)&&g.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")u={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")u={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")u={function_calling_config:{mode:"ANY"}};else{let g=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};u={function_calling_config:{mode:"ANY"},...g}}else d&&(u={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(u={...u??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let p={};if(this.config.thinking?.includeThoughts&&(p.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(p.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(p.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let g=this.config.thinkingTokenBudgetLevels,f=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":p.thinkingBudget=0,p.includeThoughts=!1,delete p.thinkingLevel;break;case"minimal":p.thinkingBudget=g?.minimal??200,f&&(p.thinkingLevel="low");break;case"low":p.thinkingBudget=g?.low??800,f&&(p.thinkingLevel="low");break;case"medium":p.thinkingBudget=g?.medium??5e3,f&&(p.thinkingLevel="high");break;case"high":p.thinkingBudget=g?.high??1e4,f&&(p.thinkingLevel="high");break;case"highest":p.thinkingBudget=g?.highest??24500,f&&(p.thinkingLevel="high");break}}p.thinkingLevel&&delete p.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(p.includeThoughts=t.showThoughts);let m={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(p).length>0?{thinkingConfig:p}:{}};if(e.responseFormat){if(m.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let g=e.responseFormat.schema.schema||e.responseFormat.schema;m.responseSchema=br(g)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(m.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:u,systemInstruction:a,generationConfig:m,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new ae("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new ae("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new ae("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new ae("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new ae("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new ae("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new ae("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new ae("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new ae("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let c of o.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){s.thought=c.text;let u=c.thoughtSignature||c.thought_signature;s.thoughtBlock={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;u&&(s.thoughtBlock?s.thoughtBlock.signature=u:s.thoughtBlock={data:"",encrypted:!1,signature:u}),s.functionCalls=[...s.functionCalls??[],{id:xe(),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});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}}},Dt=class i extends de{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,d;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let g;r?g="endpoints":g="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let p={...ss(),...o},m=new os(p,c,r,e,s);l=[...yr,...l??[]];let h=g=>{let f=Me({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},A=a?.map(g=>{let f=g,x=f?.config;if(!x)return g;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let I={...f};Object.keys(b).length>0&&(I.modelConfig={...f.modelConfig??{},...b});let S=x.thinking?.thinkingTokenBudget;if(typeof S=="number"){let T=p.thinkingTokenBudgetLevels,w=[["minimal",T?.minimal??200],["low",T?.low??800],["medium",T?.medium??5e3],["high",T?.high??1e4],["highest",T?.highest??24500]],y="minimal",k=Number.POSITIVE_INFINITY;for(let[E,M]of w){let R=Math.abs(S-M);R<k&&(k=R,y=E)}I.thinkingTokenBudget=y}return x.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!x.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:u,headers:d,modelInfo:l,defaults:{model:p.model,embedModel:p.embedModel},options:s,supportFor:h,models:A??a})}};var Zl=new Ce,$t=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(Zl.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 Rn=(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))(Rn||{});var Ir=[{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 ec=()=>structuredClone({model:"llama-3.3-70b-versatile",...X()}),Lt=class extends pe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...ec(),...t},a={...n,streamingUsage:!1};o=[...Ir,...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 $t(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 Tr=[];var Cr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Cr||{});var as=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...X()}),Wi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...me()}),is=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
|
|
153
153
|
${JSON.stringify(e.functions,null,2)}
|
|
154
154
|
`:"",r=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let c=l.functionCalls?.map(u=>{let d=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${d})`}).join(`
|
|
155
155
|
`);return c?`Assistant: ${l.content}
|
|
@@ -183,7 +183,7 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
|
|
|
183
183
|
|
|
184
184
|
`,o+=c.length)}else r=`${s}
|
|
185
185
|
|
|
186
|
-
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},ic=(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 nn=require("@opentelemetry/api");var Fn=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o,index: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,thoughtBlock: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,thoughtBlock:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(o&&typeof o=="object"){let c=l.value.thoughtBlock??{},u={data:(c.data??"")+(o.data??""),encrypted:!!c.encrypted||!!o.encrypted,...o.signature?{signature:o.signature}:{}};l.value.thoughtBlock=u}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(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}},Xt=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Fn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Fn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)St(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 Fn):this.defaultMemory.reset()}};var Ve=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()}},Gr=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 Ve({message:o});if(!o)throw r?new Ve({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},ys=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 Ve({message:c});if(!c&&a)throw new Ve({message:a})}}};var bs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},_n,Is=i=>{if(_n)return _n;let e=i??Q.meter;if(e)return _n=ac(e),_n};var ia=()=>{let i=[];return Q.meter||i.push("Global meter not initialized"),!_n&&Q.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},ac=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"})}),Ur=bs,aa=i=>{Ur={...Ur,...i}},la=()=>({...Ur}),He=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Ur.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ca=(i,e,t,n,r,o)=>{try{let s=He({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Br=(i,e,t,n)=>{try{let r=He({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,r),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,r),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Ts=(i,e,t)=>{try{let n=He({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ua=(i,e)=>{try{let t=He({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Cs=(i,e,t,n,r)=>{try{let o=He({success:t.toString(),...r?{signature:r}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,o),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,o),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,o),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},pa=(i,e,t,n,r=!1,o)=>{try{let s=He({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},da=(i,e,t,n)=>{try{let r=He({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,r),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},ma=(i,e,t,n,r)=>{try{let o=He({is_streaming:e.toString(),...r?{signature:r}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,o),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,o),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},ga=(i,e,t,n,r)=>{try{let o=He({result_picker_used:t.toString(),...r?{signature:r}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,o),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,o),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},ha=(i,e,t,n,r,o)=>{try{let s=He({...o?{signature:o}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(r,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},jr=(i,e,t,n)=>{try{let r=He({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,r);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,r);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,r);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var Zt=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";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e},ge=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},fa=i=>{let t=i.map(n=>`'${n.title}' (${Zt(n.type)})`).join(", ");return new ge(`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 ${Zt(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},qr=i=>new ge(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${Zt(i.type)} value directly after.`);var zr=i=>new ge(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${Zt(i.type)}. Do not use null, undefined, or leave it blank.`),Aa=(i,e)=>new ge(`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.`),xa=(i,e)=>new ge(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${Zt(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),ya=(i,e,t)=>new ge(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${Zt(i.type)}. Ensure formatting exactly matches the expected type.`),ba=(i,e,t)=>new ge(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Ia=(i,e,t)=>new ge(`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}.`),Rs=(i,e,t)=>new ge(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),en=(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 ge(r)},ws=(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 ge(r)};var Ta=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";ci(i,e,l,n)}return r&&Ts(r,"validation",o),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ca=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";ui(i,e,l,n)}return r&&Ts(r,"assertion",o),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ra=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{t&&n&&pi(i,e,n),r&&ua(r,o),s&&s.addEvent("refusal.error",{message:i.toString()})};function wa(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 Wr(i,e="Schema"){if("name"in i&&"type"in i)return Hr(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let o=Hr(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Hr(i,e=!1){let t=i.type,n=wa(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};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]=Hr(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=wa(i.description,t);r.items={type:Sa(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]=Hr(a,!0),s.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Sa(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 Sa(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 Kr(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)');Kr(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))Kr(e)}var yt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Nn=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
186
|
+
`,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},ic=(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 nn=require("@opentelemetry/api");var Fn=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o,index: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,thoughtBlock: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,thoughtBlock:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(o&&typeof o=="object"){let c=l.value.thoughtBlock??{},u={data:(c.data??"")+(o.data??""),encrypted:!!c.encrypted||!!o.encrypted,...o.signature?{signature:o.signature}:{}};l.value.thoughtBlock=u}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(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}},Xt=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Fn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Fn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)St(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 Fn):this.defaultMemory.reset()}};var Ve=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()}},Gr=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 Ve({message:o});if(!o)throw r?new Ve({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},ys=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 Ve({message:c});if(!c&&a)throw new Ve({message:a})}}};var bs={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},_n,Is=i=>{if(_n)return _n;let e=i??Q.meter;if(e)return _n=ac(e),_n};var ia=()=>{let i=[];return Q.meter||i.push("Global meter not initialized"),!_n&&Q.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},ac=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"})}),Ur=bs,aa=i=>{Ur={...Ur,...i}},la=()=>({...Ur}),He=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Ur.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},ca=(i,e,t,n,r,o)=>{try{let s=He({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Br=(i,e,t,n)=>{try{let r=He({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,r),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,r),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Ts=(i,e,t)=>{try{let n=He({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ua=(i,e)=>{try{let t=He({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Cs=(i,e,t,n,r)=>{try{let o=He({success:t.toString(),...r?{signature:r}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,o),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,o),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,o),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},pa=(i,e,t,n,r=!1,o)=>{try{let s=He({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},da=(i,e,t,n)=>{try{let r=He({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,r),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},ma=(i,e,t,n,r)=>{try{let o=He({is_streaming:e.toString(),...r?{signature:r}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,o),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,o),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},ga=(i,e,t,n,r)=>{try{let o=He({result_picker_used:t.toString(),...r?{signature:r}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,o),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,o),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},ha=(i,e,t,n,r,o)=>{try{let s=He({...o?{signature:o}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(r,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},jr=(i,e,t,n)=>{try{let r=He({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,r);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,r);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,r);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var Zt=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";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e},he=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},fa=i=>{let t=i.map(n=>`'${n.title}' (${Zt(n.type)})`).join(", ");return new he(`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 ${Zt(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},qr=i=>new he(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${Zt(i.type)} value directly after.`);var zr=i=>new he(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${Zt(i.type)}. Do not use null, undefined, or leave it blank.`),Aa=(i,e)=>new he(`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.`),xa=(i,e)=>new he(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${Zt(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),ya=(i,e,t)=>new he(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${Zt(i.type)}. Ensure formatting exactly matches the expected type.`),ba=(i,e,t)=>new he(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Ia=(i,e,t)=>new he(`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}.`),Rs=(i,e,t)=>new he(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),en=(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 he(r)},ws=(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 he(r)};var Ta=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";ci(i,e,l,n)}return r&&Ts(r,"validation",o),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ca=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";ui(i,e,l,n)}return r&&Ts(r,"assertion",o),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ra=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{t&&n&&pi(i,e,n),r&&ua(r,o),s&&s.addEvent("refusal.error",{message:i.toString()})};function wa(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 Wr(i,e="Schema"){if("name"in i&&"type"in i)return Hr(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let o=Hr(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Hr(i,e=!1){let t=i.type,n=wa(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};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]=Hr(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=wa(i.description,t);r.items={type:Sa(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]=Hr(a,!0),s.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Sa(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 Sa(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 Kr(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)');Kr(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))Kr(e)}var yt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Nn=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
|
|
187
187
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Dn=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
|
|
188
188
|
${t.join(`
|
|
189
189
|
`)}`};toString(){return[`${this.name}: Function execution error in '${this.func.name}'`,...this.fields.map(t=>{let n=this.getFieldDescription(t.field);return` - ${t.field}: ${t.message}${n?` (${n})`:""}`}),this.funcId?` Function ID: ${this.funcId}`:""].join(`
|
|
@@ -194,10 +194,10 @@ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } }
|
|
|
194
194
|
`)+A.title}:`,x=Da(n,f,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(p===-1||x<p)&&(p=x,m=f.length,u=h,d=A)}if(p===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&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 h=s.find(A=>!A.isOptional);if(h)throw qr(h)}break}if(a&&d&&a.name!==d.name)throw qr(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let h=n.substring(t.s,p).trim(),A=Yr(t.currField,h);A!==void 0&&(e[t.currField.name]=A),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:p}):t.prevFields=[{field:t.currField,s:t.s,e:p}]}t.s=p+m,d!==void 0&&u!==void 0&&(t.currField=d,t.currFieldIndex=u),d&&!t.extractedFields.includes(d)&&t.extractedFields.push(d),d&&t.streamedIndex[d.name]===void 0&&(t.streamedIndex[d.name]=0)}},Es=(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 h=`
|
|
195
195
|
${m.title}:`,A=n.indexOf(h,t.s);A!==-1&&A<c&&(c=A)}let d=n.substring(t.s,c).trim(),p=Yr(t.currField,d);p!==void 0&&(e[t.currField.name]=p)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let d=i.getOutputFields().find(p=>!p.isOptional);if(d)throw qr(d)}if(dc(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Os(t,e,i.getOutputFields()):c||Os(t,e,i.getOutputFields())}},dc=(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=`
|
|
196
196
|
${s.title}:`,d=t.indexOf(u,c),p=t.substring(c,d===-1?t.length:d).trim();if(p)try{let m=Yr(s,p);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
|
|
197
|
-
`);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 d=Yr(s,u);if(d!==void 0){e[s.name]=d;break}}catch(d){if(!s.isOptional)throw d}break}}}},$a=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Ga(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 Pa(i,e,t);case"datetime":return Fa(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*La(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,d=u===0,p=(t<0?0:t)+u,m=i.substring(p,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let A=d?h.trimStart():h;r.currField?.type?.name==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:o,delta:{[s]:A}},r.streamedIndex[s]=u+h.length)}function*Ps(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*La(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*La(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,d=l.slice(u);d&&d.length>0&&(yield{index:r,delta:{[s]:d}},n.streamedIndex[s]=u+d.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 d=c.substring(u);yield{index:r,delta:{[s]:d}},n.streamedIndex[s]=c.length}}}}function Yr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw zr(i)}let t;if(i.type?.name==="json")try{let r=Ga(e);return t=JSON.parse(r),t}catch(r){throw Aa(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Na(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw xa(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;t[r]=$a(i,s,!0)}}else t=$a(i,e)}catch(r){throw ya(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&<(t,i),(n.name==="string"||n.name==="code")&&_e(t,i),n.name==="number"&&Ne(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?_e(r,i):n.name==="number"&&Ne(r,i));return t}function eo(i,e){let t=i.getOutputFields();for(let n of t){let r=e[n.name];if(r==null){if(!n.isOptional)throw zr(n);continue}let o=n.type;if(o){if(o.name==="url"&<(r,n),(o.name==="string"||o.name==="code")&&_e(r,n),o.name==="number"&&Ne(r,n),o.isArray&&Array.isArray(r))for(let s of r)s!=null&&(o.name==="url"?lt(s,n):o.name==="string"||o.name==="code"?_e(s,n):o.name==="number"&&Ne(s,n));if(o.name==="object"&&o.fields&&typeof r=="object"&&Xr(n,r),o.isArray&&o.fields&&Array.isArray(r)&&o.name==="object")for(let s of r)s&&typeof s=="object"&&Xr(n,s)}}}function Xr(i,e){let t=i.type?.fields;if(!(!t||typeof t!="object"))for(let[n,r]of Object.entries(t)){let o={name:n,title:n,description:r.description,type:{name:r.type,isArray:r.isArray,options:r.options,fields:r.fields,minLength:r.minLength,maxLength:r.maxLength,minimum:r.minimum,maximum:r.maximum,pattern:r.pattern,patternDescription:r.patternDescription,format:r.format},isOptional:r.isOptional??!1,isInternal:r.isInternal??!1},s=e[o.name];if(s==null){if(!o.isOptional)throw zr(o);continue}let a=o.type;if(a){if(a.name==="url"&<(s,o),(a.name==="string"||a.name==="code")&&_e(s,o),a.name==="number"&&Ne(s,o),a.isArray&&Array.isArray(s))for(let l of s)l!=null&&(a.name==="url"?lt(l,o):a.name==="string"||a.name==="code"?_e(l,o):a.name==="number"&&Ne(l,o));if(a.name==="object"&&a.fields&&typeof s=="object"&&!Array.isArray(s)&&Xr(o,s),a.isArray&&a.fields&&Array.isArray(s)&&a.name==="object")for(let l of s)l&&typeof l=="object"&&Xr(o,l)}}}var Ga=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Fs(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});Ua(r.field,t,s,n)}}async function _s(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});Ua(t.currField,n,u,o)}}var Ua=(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=mc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function mc(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*Ba({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 d=u;d.modelUsage&&(s=d.modelUsage);for(let p of d.results){if(Array.isArray(p.citations))for(let h of p.citations)h?.url&&a.push({url:h.url,title:h.title,description:h.description,license:h.license,publicationDate:h.publicationDate,snippet:h.snippet});if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&!p.thoughtBlock&&(!p.functionCalls||p.functionCalls.length===0))continue;let m=t.find(h=>h.index===p.index);if(!m)throw new Error(`No state found for result (index: ${p.index})`);yield*gc({...r,result:p,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*hc({...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*gc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:d}){if(i.functionCalls&&i.functionCalls.length>0)rr(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,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,delta:i.content,index:i.index},t);let p=a.getOutputFields();if(p.some(A=>A.type?.name==="object"||A.type?.isArray&&A.type.fields)){let A=ka(s.content);if(A&&typeof A=="object"){let g={};for(let f of Object.keys(A))p.some(x=>x.name===f)&&(g[f]=A[f]);eo(a,g),Object.assign(s.values,g),yield{index:i.index,delta:g};return}}if(Ms(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await ys(u,s.xstate,s.content),l.length!==0&&await _s(l,s.content,s.xstate,e,s.values,t),yield*Ps(a,s.content,s.values,s.xstate,i.index),await Gr(d,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,thoughtBlock:i.thoughtBlock},t)):i.thoughtBlock&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlock:i.thoughtBlock},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
197
|
+
`);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 d=Yr(s,u);if(d!==void 0){e[s.name]=d;break}}catch(d){if(!s.isOptional)throw d}break}}}},$a=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Ga(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 Pa(i,e,t);case"datetime":return Fa(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*La(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,d=u===0,p=(t<0?0:t)+u,m=i.substring(p,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let A=d?h.trimStart():h;r.currField?.type?.name==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:o,delta:{[s]:A}},r.streamedIndex[s]=u+h.length)}function*Ps(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*La(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*La(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,d=l.slice(u);d&&d.length>0&&(yield{index:r,delta:{[s]:d}},n.streamedIndex[s]=u+d.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 d=c.substring(u);yield{index:r,delta:{[s]:d}},n.streamedIndex[s]=c.length}}}}function Yr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw zr(i)}let t;if(i.type?.name==="json")try{let r=Ga(e);return t=JSON.parse(r),t}catch(r){throw Aa(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Na(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw xa(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;t[r]=$a(i,s,!0)}}else t=$a(i,e)}catch(r){throw ya(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&<(t,i),(n.name==="string"||n.name==="code")&&_e(t,i),n.name==="number"&&Ne(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?_e(r,i):n.name==="number"&&Ne(r,i));return t}function eo(i,e){let t=i.getOutputFields();for(let n of t){let r=e[n.name];if(r==null){if(!n.isOptional)throw zr(n);continue}let o=n.type;if(o){if(o.name==="url"&<(r,n),(o.name==="string"||o.name==="code")&&_e(r,n),o.name==="number"&&Ne(r,n),o.isArray&&Array.isArray(r))for(let s of r)s!=null&&(o.name==="url"?lt(s,n):o.name==="string"||o.name==="code"?_e(s,n):o.name==="number"&&Ne(s,n));if(o.name==="object"&&o.fields&&typeof r=="object"&&Xr(n,r),o.isArray&&o.fields&&Array.isArray(r)&&o.name==="object")for(let s of r)s&&typeof s=="object"&&Xr(n,s)}}}function Xr(i,e){let t=i.type?.fields;if(!(!t||typeof t!="object"))for(let[n,r]of Object.entries(t)){let o={name:n,title:n,description:r.description,type:{name:r.type,isArray:r.isArray,options:r.options,fields:r.fields,minLength:r.minLength,maxLength:r.maxLength,minimum:r.minimum,maximum:r.maximum,pattern:r.pattern,patternDescription:r.patternDescription,format:r.format},isOptional:r.isOptional??!1,isInternal:r.isInternal??!1},s=e[o.name];if(s==null){if(!o.isOptional)throw zr(o);continue}let a=o.type;if(a){if(a.name==="url"&<(s,o),(a.name==="string"||a.name==="code")&&_e(s,o),a.name==="number"&&Ne(s,o),a.isArray&&Array.isArray(s))for(let l of s)l!=null&&(a.name==="url"?lt(l,o):a.name==="string"||a.name==="code"?_e(l,o):a.name==="number"&&Ne(l,o));if(a.name==="object"&&a.fields&&typeof s=="object"&&!Array.isArray(s)&&Xr(o,s),a.isArray&&a.fields&&Array.isArray(s)&&a.name==="object")for(let l of s)l&&typeof l=="object"&&Xr(o,l)}}}var Ga=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Fs(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});Ua(r.field,t,s,n)}}async function _s(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});Ua(t.currField,n,u,o)}}var Ua=(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=mc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function mc(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*Ba({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 d=u;d.modelUsage&&(s=d.modelUsage);for(let p of d.results){if(Array.isArray(p.citations))for(let h of p.citations)h?.url&&a.push({url:h.url,title:h.title,description:h.description,license:h.license,publicationDate:h.publicationDate,snippet:h.snippet});if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&!p.thoughtBlock&&(!p.functionCalls||p.functionCalls.length===0))continue;let m=t.find(h=>h.index===p.index);if(!m)throw new Error(`No state found for result (index: ${p.index})`);yield*gc({...r,result:p,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*hc({...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*gc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:d}){if(i.functionCalls&&i.functionCalls.length>0)rr(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,thoughtBlock:i.thoughtBlock,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,thoughtBlock:i.thoughtBlock,delta:i.content,index:i.index},t);let p=a.getOutputFields();if(p.some(A=>A.type?.name==="object"||A.type?.isArray&&A.type.fields)){let A=ka(s.content);if(A&&typeof A=="object"){let g={};for(let f of Object.keys(A))p.some(x=>x.name===f)&&(g[f]=A[f]);eo(a,g),Object.assign(s.values,g),yield{index:i.index,delta:g};return}}if(Ms(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await ys(u,s.xstate,s.content),l.length!==0&&await _s(l,s.content,s.xstate,e,s.values,t),yield*Ps(a,s.content,s.values,s.xstate,i.index),await Gr(d,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,thoughtBlock:i.thoughtBlock},t)):i.thoughtBlock&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlock:i.thoughtBlock},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
198
198
|
Content: ${s.content}`)}async function*hc({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:d,asserts:p,fieldProcessors:m,streamingFieldProcessors:h,functionResultFormatter:A,signatureToolCallingManager:g,logger:f,debug:x,stopFunctionNames:b}){let I=g?void 0:Ss(t,i.functionCalls,i.values,n);if(I){if(!r)throw new Error("Functions are not defined");let S=await Jr({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:b});i.functionsExecuted=new Set([...i.functionsExecuted,...S]),i.functionCalls=[]}else{let S=e.getOutputFields(),T=S.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields),w=!1;if(T)try{let y=JSON.parse(i.content),k={};for(let E of Object.keys(y))S.some(M=>M.name===E)&&(k[E]=y[E]);eo(e,k),Object.assign(i.values,k),yield{index:i.index,delta:k},w=!0}catch(y){let k=(y.message||"").toLowerCase();if(k.includes("at least")||k.includes("at most")||k.includes("must match pattern")||k.includes("invalid url")||k.includes("required")||k.includes("missing")||k.includes("valid email")||k.includes("number must be"))throw y}if(!w){let y=g!==void 0;Es(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:y,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(g){let y=await g.processResults(i.values);if(y&&y.length>0){if(!r)throw new Error("Functions are not defined");let k=await Jr({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:b});i.functionsExecuted=new Set([...i.functionsExecuted,...k]),o.updateResult({name:void 0,content:i.content,functionCalls:y.map(E=>({id:E.id,type:"function",function:{name:E.name,params:E.args}})),index:i.index},s);return}}await ys(d,i.xstate,i.content,!0),await Gr(p,i.values),m.length&&await Fs(m,i.values,o,s),h.length!==0&&await _s(h,i.content,i.xstate,o,i.values,s,!0),yield*Ps(e,i.content,i.values,i.xstate,i.index)}}async function*ja({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:d,fieldProcessors:p,thoughtFieldName:m,signature:h,functionResultFormatter:A,logger:g,debug:f,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:I}){let S=e.results??[],T=x!==void 0;t.addResponse(S,n);let w=[];for(let M of S)if(Array.isArray(M?.citations))for(let R of M.citations)R?.url&&w.push({url:R.url,title:R.title,description:R.description,license:R.license,publicationDate:R.publicationDate,snippet:R.snippet});for(let M of S){let R=l[M.index];if(!R)throw new Error(`No state found for result (index: ${M.index})`);if(e.modelUsage){let P=Array.from(new Map(w.filter(v=>v.url).map(v=>[v.url,v])).values()),C={...e.modelUsage,...P.length?{citations:P}:{}};if(c.push(C),f&&g){let v=structuredClone(C);delete v.citations,g({name:"ChatResponseUsage",value:v}),C.citations&&C.citations.length>0&&g({name:"ChatResponseCitations",value:C.citations})}}if(x&&M.content){M.thought&&M.thought.length>0&&(R.values[m]=M.thought),Zr(h,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T});let C=(await x.processResults(R.values))?.map(v=>({id:v.id,type:"function",function:{name:v.name,params:v.args}}));C&&C.length>0&&t.updateResult({name:M.name,content:M.content,functionCalls:C,index:M.index},n)}if(M.functionCalls?.length){let P=Ss(i,M.functionCalls,R.values);if(P&&P.length>0){if(!o)throw new Error("Functions are not defined");let C;try{C=await Jr({ai:i,functionList:o,functionCalls:P,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:u,index:M.index,functionResultFormatter:A,logger:g,debug:f,stopFunctionNames:b})}catch(v){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),v}R.functionsExecuted=new Set([...R.functionsExecuted,...C])}}else if(M.content){M.thought&&M.thought.length>0&&(R.values[m]=M.thought);let P=h.getOutputFields();if(P.some(v=>v.type?.name==="object"||v.type?.isArray&&v.type.fields))try{let v=JSON.parse(M.content),O={};for(let $ of Object.keys(v))P.some(Y=>Y.name===$)&&(O[$]=v[$]);eo(h,O),Object.assign(R.values,O)}catch(v){if(v.name?.includes("ValidationError")||v.name?.includes("Error")){let O=(v.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 v}Zr(h,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}else Zr(h,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}if(await Gr(d,R.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),p.length&&await Fs(p,R.values,t,n),M.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
199
199
|
Content: ${M.content}`)}let y=l.map(M=>M.values);for(let M of y)for(let R of h.getOutputFields())R.isInternal&&delete M[R.name];let k=h.getOutputFields(),E=y.map((M,R)=>{let P={};for(let C of k)C.isInternal||(P[C.name]=M[C.name]);return M[m]!==void 0&&(P[m]=M[m]),{index:R,delta:P}});for(let M of E)yield M}function qa(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(d=>s.functionsExecuted.has(d)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",u=r.tags?r.tags.some(d=>d==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var tn=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 U=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Ns=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new U("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 U("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 U('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 U(`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 U)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new U(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new U(`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 U(`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 U(`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 U("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new U("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
|
|
200
|
-
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new U(`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 U?r:new U(`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 U(`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 U?r:new U(`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 U(`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 U(`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 U?o:new U(`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 U(`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 U(`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 U(`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 U(`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 U(`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 U(`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 U?s:new U(`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(Q.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 U(`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 U(`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 U(`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 U(`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 U(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 U("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 U(`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 U(`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 U(`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 U(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function za(i){return new Ns(i).parse()}var Gn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ds(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ds(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}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new ce(e)}},he=class i{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description})}internal(){return new i({...this,isInternal:!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}},re=Object.assign(()=>new Gn,{string:i=>new he({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1}),number:i=>new he({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1}),boolean:i=>new he({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1}),json:i=>new he({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1}),datetime:i=>new he({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1}),date:i=>new he({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1}),class:(i,e)=>new he({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1}),image:i=>new he({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1}),audio:i=>new he({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1}),file:i=>new he({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1}),url:i=>new he({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1}),code:(i,e)=>new he({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1}),object:(i,e)=>new he({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1})});function Ds(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,Ds(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"}},ce=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=za(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);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);Je(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);Je(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 Je(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 Je(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);Je(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);Je(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};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=>{Je(e,"input")}),this.getOutputFields().forEach(e=>{Je(e,"output")}),this.sigHash=Ee("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ka(this.description,this.inputFields,this.outputFields),[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=>{Je(e,"input")}),this.getOutputFields().forEach(e=>{Je(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Ee("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ka(this.description,this.inputFields,this.outputFields),[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"')}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 Wr(e,this.description??"Schema")}};function Ha(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 Ka(i,e,t){let n=i?`"${i}" `:"",r=e.map(Ha).join(", "),o=t.map(Ha).join(", ");return`${n}${r} -> ${o}`}function fc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function Je(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(!fc(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(Q.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&&Ac(i,e)}function Ac(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new 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&&$s(t.fields,i.name,e)}function $s(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&&$s(o.fields,s,t,n+1),o.isArray&&o.fields&&$s(o.fields,`${s}[]`,t,n+1)}}var ut=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ce(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 tn,this.key={id:this.signature.hash()}}getSignature(){return new ce(this.signature)}setSignature(e){this.signature=new ce(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&&(Qr(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 Ln(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 xc=`
|
|
200
|
+
`)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new U(`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 U?r:new U(`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 U(`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 U?r:new U(`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 U(`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 U(`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 U?o:new U(`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 U(`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 U(`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 U(`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 U(`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 U(`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 U(`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 U?s:new U(`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(Q.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 U(`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 U(`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 U(`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 U(`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 U(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 U("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 U(`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 U(`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 U(`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 U(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function za(i){return new Ns(i).parse()}var Gn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ds(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ds(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}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new ce(e)}},ge=class i{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description})}internal(){return new i({...this,isInternal:!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}},re=Object.assign(()=>new Gn,{string:i=>new ge({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1}),number:i=>new ge({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1}),boolean:i=>new ge({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1}),json:i=>new ge({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1}),datetime:i=>new ge({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1}),date:i=>new ge({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1}),class:(i,e)=>new ge({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1}),image:i=>new ge({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1}),audio:i=>new ge({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1}),file:i=>new ge({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1}),url:i=>new ge({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1}),email:i=>new ge({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,format:"email"}),code:(i,e)=>new ge({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1}),object:(i,e)=>new ge({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1})});function Ds(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,Ds(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"}},ce=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=za(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);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);Je(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);Je(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 Je(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 Je(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);Je(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);Je(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};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=>{Je(e,"input")}),this.getOutputFields().forEach(e=>{Je(e,"output")}),this.sigHash=Ee("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ka(this.description,this.inputFields,this.outputFields),[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=>{Je(e,"input")}),this.getOutputFields().forEach(e=>{Je(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Ee("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ka(this.description,this.inputFields,this.outputFields),[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"')}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 Wr(e,this.description??"Schema")}};function Ha(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 Ka(i,e,t){let n=i?`"${i}" `:"",r=e.map(Ha).join(", "),o=t.map(Ha).join(", ");return`${n}${r} -> ${o}`}function fc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function Je(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(!fc(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(Q.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&&Ac(i,e)}function Ac(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&&$s(t.fields,i.name,e)}function $s(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&&$s(o.fields,s,t,n+1),o.isArray&&o.fields&&$s(o.fields,`${s}[]`,t,n+1)}}var ut=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ce(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 tn,this.key={id:this.signature.hash()}}getSignature(){return new ce(this.signature)}setSignature(e){this.signature=new ce(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&&(Qr(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 Ln(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 xc=`
|
|
201
201
|
## Function Call Instructions
|
|
202
202
|
- Complete the task, using the functions defined earlier in this prompt.
|
|
203
203
|
- Output fields should only be generated after all functions have been called.
|
|
@@ -229,7 +229,7 @@ ${u}`),l&&l.length>0&&r.push(xc.trim()),this.sig.getOutputFields().some(m=>m.typ
|
|
|
229
229
|
`),n.push(t.map(r=>`- ${r}`).join(`
|
|
230
230
|
`))):n.push(t),[{type:"text",text:n.join("")}]}},Wa=i=>i.map(e=>`\`${e.title}\``).join(", "),bc=i=>i.map(t=>{let n=t.title,r=t.type?.name?Ja(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,s=t.description?` ${no(t.description)}`:"";return`${n}: (${o})${s}`.trim()}).join(`
|
|
231
231
|
`),Ic=i=>i.map(t=>{let n=t.title,r=t.type?.name?Ja(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:no(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(`
|
|
232
|
-
`),Tc=(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?_a(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)},Ja=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 Va(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 Cc=(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 no(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Rc(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?Rc(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 Qa(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 oo=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}=Sc(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 d=s.get(c);if(!d)continue;let p=d.get(a);if(!p)continue;let m=o.get(u.name)??{};this.setNested(m,p,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let d=(l.parameters.required||[]).filter(p=>c[p]===void 0);if(d.length>0)throw new ge(`Missing required arguments for tool '${l.name}': ${d.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[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 Sc(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 d=a?`${a}.${c}`:c,p=`${i.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=vc(u);e.push({name:Oc(p),title:kc(i.name,d),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(p,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function vc(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 kc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Oc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Za(i,e,t){let n=new ce(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=Ls(o.name),l=Xa(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Ya(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}=Mc(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=Ls(o.name),a=Xa(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:Ya(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Mc(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 d=a?`${a}.${c}`:c,p=`${i.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Ec(u),h={name:Ls(p),title:Pc(i.name,d),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(h),t.set(p,h)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ec(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 Pc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Ls(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ya(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Xa(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var Un=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new oo(e)}processSignature(e){let{signature:t}=Za(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 we=class extends ut{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:t?.cacheSystemPrompt};this.promptTemplate=new(t?.promptTemplate??bt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Vr(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Is()}updateMeter(e){Is(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:d,thinkingTokenBudget:p,showThoughts:m}=n??{},h=await Qa(t,l,{resultPicker:n?.resultPicker}),A=t?.history(h,l)??[];if(A.length===0)throw new Error("No chat prompt found");let g={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let I,S=this.signature.getOutputFields();return S.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields)&&(I={type:"json_schema",schema:{name:"output",strict:!0,schema:Wr(S)}}),await e.chat({chatPrompt:A,functions:o,functionCall:s,modelConfig:g,model:c,responseFormat:I},{sessionId:l,rateLimiter:u,stream:d,debug:f,debugHideSystemPrompt:!x,thinkingTokenBudget:p,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??Q.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,p=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,h=n?.strictMode??!1,A=n.model,g=this.usage,f=r===0,x=this.isDebug(e,n),b=this.getLogger(e,n),{functions:I,functionCall:S}=va(u,p,f,n),T=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:I,functionCall:S,stepIndex:r});T instanceof ReadableStream?yield*Ba({ai:e,model:A,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:h,span:o,states:a,usage:g,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*ja({ai:e,model:A,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:h,states:a,usage:g,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(E=>E.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,u=r.maxSteps??this.options?.maxSteps??10,d=r.mem??this.options?.mem??new Xt,p=[...this.functions,...r.functions?Vr(r.functions):[]],m=p&&p.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto",A=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&h==="prompt"&&(this.signatureToolCallingManager=new Un(p)),m&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new Un(p));let g,f,x=this.options?.promptTemplate??bt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let b={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:A};this.promptTemplate=new x(this.signature,b);let I,S=performance.now();Array.isArray(t)?(Pi(t),I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-S,w=this.getMetricsInstruments();w&&jr(w,"prompt_render",T,this.getSignatureName());let y=performance.now();d.addRequest(I,r.sessionId);let k=performance.now()-y;w&&jr(w,"memory_update",k,this.getSignatureName());e:for(let E=0;E<u;E++){for(let R=0;R<c;R++)try{let P=this.forwardCore({options:r,ai:e,mem:d,stepIndex:E,span:o,traceContext:s,states:n,stopFunctionNames:l}),C=!1;try{for await(let $ of P)$!==void 0&&(yield{version:R,index:$.index,delta:$.delta})}catch($){if($ instanceof yt)C=!0;else throw $}if(C?!1:qa(d,l,n,r?.sessionId)){let $=this.getMetricsInstruments();$&&Br($,E+1,u,this.getSignatureName());continue e}r?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",r.sessionId),d.removeByTag("correction",r.sessionId),d.removeByTag("error",r.sessionId));let O=this.getMetricsInstruments();if(O){Br(O,E+1,u,this.getSignatureName());let $=new Set;n.forEach(Y=>{Y.functionsExecuted.forEach(W=>$.add(W))}),$.size>0&&pa(O,!0,$.size,!0,!1,this.getSignatureName()),da(O,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(P){f=P;let C,v=this.isDebug(e,r),O=this.getLogger(e,r),$=this.getMetricsInstruments(),Y=this.getSignatureName(),W={error:P,errCount:R,logger:O,metricsInstruments:$,signatureName:Y,span:o,debug:v};if(o?.recordException(P),P instanceof ge)C=Ta(W),g=P;else if(P instanceof Ve)C=Ca(W),g=P;else if(P instanceof ae)Ra(W);else if(!(P instanceof Be))throw Gs(P,e,this.signature);C&&(d.addTag("error",r.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(C)}],r.sessionId),d.addTag("correction",r.sessionId))}let M=this.getMetricsInstruments();throw M&&Cs(M,c,!1,c,this.getSignatureName()),Gs(new Error(`Unable to fix validation error: ${(g??f)?.message??(g??f)?.toString()??"unknown error"}`),e,this.signature)}throw w&&Br(w,u,u,this.getSignatureName()),Gs(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&<(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&_e(r,n),o.name==="number"&&Ne(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let s=0;s<r.length;s++){let a=r[s];o.name==="string"||o.name==="code"?_e(a,n):o.name==="number"?Ne(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${s}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let s=e[r];if(o.isOptional&&s===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?_e(s,a):o.type==="number"?Ne(s,a):o.type==="object"&&o.fields&&typeof s=="object"&&s!==null&&this.validateObjectFields(s,o.fields,a.name),o.isArray&&Array.isArray(s))for(let l=0;l<s.length;l++){let c=s[l];o.type==="string"||o.type==="code"?_e(c,a):o.type==="number"?Ne(c,a):o.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(f=>"role"in f))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments();a&&jr(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=Vr(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},p=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=p?`AxGen > ${p}`:"AxGen",h=l.startSpan(m,{kind:nn.SpanKind.SERVER,attributes:d}),A=nn.context.active(),g=nn.trace.setSpan(A,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},h,g),!this.excludeContentFromTrace){let f=o.map(b=>b.values),x=f.length===1?f[0]:f;h.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{h.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Q.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,p)})();if(r&&o){let p=await r(o);if(p!==void 0)return p}let s=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,d=!1;try{let p=this.getMetricsInstruments();p&&ha(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),h=[],A=0,g=0;for await(let w of m)w.version!==A&&(h=[]),A=w.version,h=ks(h,w),g++;u=A;let f=performance.now();d=!!n?.resultPicker;let x=await ro(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),b=performance.now()-f,S=h[x]?.delta??{},T=Array.isArray(t)?{}:t??{};if(this.trace={...T,...S},d&&this.isDebug(e,n)){let w=this.getLogger(e,n);gi(h.length,x,b,w)}if(c=!0,p&&(ga(p,h.length,d,d?b:void 0,a),ma(p,l,g,void 0,a)),r&&o)try{await r(o,S)}catch{}return S}catch(p){throw c=!1,p}finally{let p=performance.now()-s,m=this.getMetricsInstruments();m&&(ca(m,p,c,a,e.getName(),n?.model?String(n.model):void 0),u>0&&Cs(m,u,c,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Q.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(p=>p.name);return this.computeCacheKey(t,d)})();if(r&&o){let d;try{d=await r(o)}catch{}if(d!==void 0){yield{version:0,index:0,delta:d};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let s=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let d of s)d.version!==l&&(a=[]),l=d.version,a=ks(a,d);let c=await ro(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&o)try{await r(o,u.delta)}catch{}yield{version:l,index:c,delta:u.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??Q.logger??e.getLogger()}computeCacheKey(e,t){let n=Ee("sha256");n.update(this.signature.hash()??"");let r=o=>{let s=typeof o;if(n.update(`|${s}|`),o==null){n.update("null");return}if(s==="string"||s==="number"||s==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=Ee("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let s=t.map(a=>o.values?.[a]);for(let a of s)r(a)}else{let o=t.map(s=>e?.[s]);for(let s of o)r(s)}return n.digest("hex")}},Bn=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function Gs(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let s=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:s,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Bn("Generate failed",l,{cause:n})}var Fc=i=>i.replace(/^\W+|\W+$/g,""),_c=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},Nc=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Dc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},$c=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Lc=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},so={trimNonAlphaNum:Fc,splitIntoTwo:_c,dedup:Nc,extractIdAndText:Dc,extractIndexPrefixedText:$c,batchArray:Lc};var io=class extends we{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
|
|
232
|
+
`),Tc=(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?_a(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)},Ja=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 Va(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 Cc=(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 no(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Rc(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?Rc(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 Qa(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 oo=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}=Sc(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 d=s.get(c);if(!d)continue;let p=d.get(a);if(!p)continue;let m=o.get(u.name)??{};this.setNested(m,p,l),o.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let d=(l.parameters.required||[]).filter(p=>c[p]===void 0);if(d.length>0)throw new he(`Missing required arguments for tool '${l.name}': ${d.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[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 Sc(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 d=a?`${a}.${c}`:c,p=`${i.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=vc(u);e.push({name:Oc(p),title:kc(i.name,d),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(p,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function vc(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 kc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Oc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Za(i,e,t){let n=new ce(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=Ls(o.name),l=Xa(o.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Ya(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}=Mc(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=Ls(o.name),a=Xa(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:Ya(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Mc(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 d=a?`${a}.${c}`:c,p=`${i.name}.${d}`;if(u.type==="object"&&u.properties)o(u.properties,d,u.required||[]);else{let m=Ec(u),h={name:Ls(p),title:Pc(i.name,d),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(h),t.set(p,h)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Ec(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 Pc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Ls(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ya(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Xa(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var Un=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new oo(e)}processSignature(e){let{signature:t}=Za(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 we=class extends ut{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:t?.cacheSystemPrompt};this.promptTemplate=new(t?.promptTemplate??bt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Vr(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Is()}updateMeter(e){Is(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:d,thinkingTokenBudget:p,showThoughts:m}=n??{},h=await Qa(t,l,{resultPicker:n?.resultPicker}),A=t?.history(h,l)??[];if(A.length===0)throw new Error("No chat prompt found");let g={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},f=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let I,S=this.signature.getOutputFields();return S.some(y=>y.type?.name==="object"||y.type?.isArray&&y.type.fields)&&(I={type:"json_schema",schema:{name:"output",strict:!0,schema:Wr(S)}}),await e.chat({chatPrompt:A,functions:o,functionCall:s,modelConfig:g,model:c,responseFormat:I},{sessionId:l,rateLimiter:u,stream:d,debug:f,debugHideSystemPrompt:!x,thinkingTokenBudget:p,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??Q.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:u}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,p=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,h=n?.strictMode??!1,A=n.model,g=this.usage,f=r===0,x=this.isDebug(e,n),b=this.getLogger(e,n),{functions:I,functionCall:S}=va(u,p,f,n),T=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:I,functionCall:S,stepIndex:r});T instanceof ReadableStream?yield*Ba({ai:e,model:A,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:h,span:o,states:a,usage:g,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*ja({ai:e,model:A,res:T,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:h,states:a,usage:g,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:b,debug:x,functionResultFormatter:d,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(E=>E.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,u=r.maxSteps??this.options?.maxSteps??10,d=r.mem??this.options?.mem??new Xt,p=[...this.functions,...r.functions?Vr(r.functions):[]],m=p&&p.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto",A=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&h==="prompt"&&(this.signatureToolCallingManager=new Un(p)),m&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new Un(p));let g,f,x=this.options?.promptTemplate??bt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let b={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:A};this.promptTemplate=new x(this.signature,b);let I,S=performance.now();Array.isArray(t)?(Pi(t),I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):I=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-S,w=this.getMetricsInstruments();w&&jr(w,"prompt_render",T,this.getSignatureName());let y=performance.now();d.addRequest(I,r.sessionId);let k=performance.now()-y;w&&jr(w,"memory_update",k,this.getSignatureName());e:for(let E=0;E<u;E++){for(let R=0;R<c;R++)try{let P=this.forwardCore({options:r,ai:e,mem:d,stepIndex:E,span:o,traceContext:s,states:n,stopFunctionNames:l}),C=!1;try{for await(let $ of P)$!==void 0&&(yield{version:R,index:$.index,delta:$.delta})}catch($){if($ instanceof yt)C=!0;else throw $}if(C?!1:qa(d,l,n,r?.sessionId)){let $=this.getMetricsInstruments();$&&Br($,E+1,u,this.getSignatureName());continue e}r?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",r.sessionId),d.removeByTag("correction",r.sessionId),d.removeByTag("error",r.sessionId));let O=this.getMetricsInstruments();if(O){Br(O,E+1,u,this.getSignatureName());let $=new Set;n.forEach(Y=>{Y.functionsExecuted.forEach(W=>$.add(W))}),$.size>0&&pa(O,!0,$.size,!0,!1,this.getSignatureName()),da(O,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(P){f=P;let C,v=this.isDebug(e,r),O=this.getLogger(e,r),$=this.getMetricsInstruments(),Y=this.getSignatureName(),W={error:P,errCount:R,logger:O,metricsInstruments:$,signatureName:Y,span:o,debug:v};if(o?.recordException(P),P instanceof he)C=Ta(W),g=P;else if(P instanceof Ve)C=Ca(W),g=P;else if(P instanceof ae)Ra(W);else if(!(P instanceof Be))throw Gs(P,e,this.signature);C&&(d.addTag("error",r.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(C)}],r.sessionId),d.addTag("correction",r.sessionId))}let M=this.getMetricsInstruments();throw M&&Cs(M,c,!1,c,this.getSignatureName()),Gs(new Error(`Unable to fix validation error: ${(g??f)?.message??(g??f)?.toString()??"unknown error"}`),e,this.signature)}throw w&&Br(w,u,u,this.getSignatureName()),Gs(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&<(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&_e(r,n),o.name==="number"&&Ne(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let s=0;s<r.length;s++){let a=r[s];o.name==="string"||o.name==="code"?_e(a,n):o.name==="number"?Ne(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${s}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let s=e[r];if(o.isOptional&&s===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?_e(s,a):o.type==="number"?Ne(s,a):o.type==="object"&&o.fields&&typeof s=="object"&&s!==null&&this.validateObjectFields(s,o.fields,a.name),o.isArray&&Array.isArray(s))for(let l=0;l<s.length;l++){let c=s[l];o.type==="string"||o.type==="code"?_e(c,a):o.type==="number"?Ne(c,a):o.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(f=>"role"in f))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments();a&&jr(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=Vr(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let u=c?.map(f=>f.name).join(","),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...u?{provided_functions:u}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},p=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=p?`AxGen > ${p}`:"AxGen",h=l.startSpan(m,{kind:nn.SpanKind.SERVER,attributes:d}),A=nn.context.active(),g=nn.trace.setSpan(A,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},h,g),!this.excludeContentFromTrace){let f=o.map(b=>b.values),x=f.length===1?f[0]:f;h.addEvent("output",{content:JSON.stringify(x,null,2)})}}finally{h.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Q.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,p)})();if(r&&o){let p=await r(o);if(p!==void 0)return p}let s=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,d=!1;try{let p=this.getMetricsInstruments();p&&ha(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),h=[],A=0,g=0;for await(let w of m)w.version!==A&&(h=[]),A=w.version,h=ks(h,w),g++;u=A;let f=performance.now();d=!!n?.resultPicker;let x=await ro(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),b=performance.now()-f,S=h[x]?.delta??{},T=Array.isArray(t)?{}:t??{};if(this.trace={...T,...S},d&&this.isDebug(e,n)){let w=this.getLogger(e,n);gi(h.length,x,b,w)}if(c=!0,p&&(ga(p,h.length,d,d?b:void 0,a),ma(p,l,g,void 0,a)),r&&o)try{await r(o,S)}catch{}return S}catch(p){throw c=!1,p}finally{let p=performance.now()-s,m=this.getMetricsInstruments();m&&(ca(m,p,c,a,e.getName(),n?.model?String(n.model):void 0),u>0&&Cs(m,u,c,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Q.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(p=>p.name);return this.computeCacheKey(t,d)})();if(r&&o){let d;try{d=await r(o)}catch{}if(d!==void 0){yield{version:0,index:0,delta:d};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let s=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let d of s)d.version!==l&&(a=[]),l=d.version,a=ks(a,d);let c=await ro(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&o)try{await r(o,u.delta)}catch{}yield{version:l,index:c,delta:u.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??Q.logger??e.getLogger()}computeCacheKey(e,t){let n=Ee("sha256");n.update(this.signature.hash()??"");let r=o=>{let s=typeof o;if(n.update(`|${s}|`),o==null){n.update("null");return}if(s==="string"||s==="number"||s==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=Ee("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let s=t.map(a=>o.values?.[a]);for(let a of s)r(a)}else{let o=t.map(s=>e?.[s]);for(let s of o)r(s)}return n.digest("hex")}},Bn=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function Gs(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let s=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:s,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Bn("Generate failed",l,{cause:n})}var Fc=i=>i.replace(/^\W+|\W+$/g,""),_c=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},Nc=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Dc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},$c=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Lc=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},so={trimNonAlphaNum:Fc,splitIntoTwo:_c,dedup:Nc,extractIdAndText:Dc,extractIndexPrefixedText:$c,batchArray:Lc};var io=class extends we{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
|
|
233
233
|
query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=so.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=o[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var ao=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var Rh=new Ce,lo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},co=class{ai;db;debug;constructor(e){this.db=new at,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}let s=o.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var el=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function tl(i,e){return i.filter(t=>!e.has(t))}function nl(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function It(i){let e=i.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function Gc(i,e){return It(i)===It(e)?1:0}function Uc(i,e){let t=It(i).split(" "),n=It(e).split(" "),r=nl(t),o=nl(n),s=0;for(let c in r){let u=r[c]??0,d=o[c]??0;s+=Math.min(u,d)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function Bc(i,e,t,n=!1){let r=It(i).split(" "),o=It(e).split(" "),s=It(t).split(" "),a=new Set([...el,...r]);o=tl(o,a),s=tl(s,a);let l=0,c=l/o.length,u=l/s.length,d=2*c*u/(c+u);return n?u:d}var rl={emScore:Gc,f1Score:Uc,novelF1ScoreOptimized:Bc};var uo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let s=0;s<n;s++){let a=this.examples[s];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),c=await e({prediction:l,example:a});r+=c}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
|
|
234
234
|
Performance: `,r,"/",n,"Average Score: ",o,`
|
|
235
235
|
`)}};var po=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 d of l)Object.hasOwn(c,d)&&(c=c[d]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);s[u]=c}),s}).filter(o=>Object.keys(o).length!==0)}};var ol=i=>{console.log(i)},Us=(i=ol)=>{let e=new Ce,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
|