@ax-llm/ax 15.0.13 → 15.0.14

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.global.js CHANGED
@@ -183,7 +183,7 @@ ${u}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
183
183
 
184
184
  `,o+=u.length)}else r=`${i}
185
185
 
186
- `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Sc=(s,e=.1)=>{let t=[...s].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var tr=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:i}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(u=>u.index===i);if(!l){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let u=l.value.thought;l.value.thought=typeof u=="string"?u+r:r}if(Array.isArray(o)&&o.length>0){let u=l.value.thoughtBlocks??[];for(let c of o){let p=u.length>0?u[u.length-1]:void 0;p&&!c.signature&&c.data?(p.data=(p.data??"")+c.data,c.encrypted&&(p.encrypted=!0)):c.signature?p&&!p.signature?(p.data=(p.data??"")+c.data,p.signature=c.signature,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):u.length===0&&u.push(structuredClone(c))}l.value.thoughtBlocks=u,u.length>0&&(l.value.thought=u.map(c=>c.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(i=>i.index===e).map(i=>i.value):o=r.find(i=>i.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(i=>({...i,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},An=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new tr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new tr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ht(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Fr(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 tr):this.defaultMemory.reset()}};var ot=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()}},po=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ot({message:o});if(!o)throw r?new ot({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Hs=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let r=s.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let i of r){let{message:a,fn:l}=i,u=await l(o,n);if(u!==void 0){if(typeof u=="string")throw new ot({message:u});if(!u&&a)throw new ot({message:a})}}};var Ks={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},nr,Ws=s=>{if(nr)return nr;let e=s??Z.meter;if(e)return nr=Oc(e),nr};var nl=()=>{let s=[];return Z.meter||s.push("Global meter not initialized"),!nr&&Z.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Oc=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),mo=Ks,rl=s=>{mo={...mo,...s}},ol=()=>({...mo}),nt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=mo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},sl=(s,e,t,n,r,o)=>{try{let i=nt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},go=(s,e,t,n)=>{try{let r=nt({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,r),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,r),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Vs=(s,e,t)=>{try{let n=nt({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},il=(s,e)=>{try{let t=nt({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Js=(s,e,t,n,r)=>{try{let o=nt({success:t.toString(),...r?{signature:r}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,o),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,o),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,o),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},al=(s,e,t,n,r=!1,o)=>{try{let i=nt({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},ll=(s,e,t,n)=>{try{let r=nt({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,r),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},ul=(s,e,t,n,r)=>{try{let o=nt({is_streaming:e.toString(),...r?{signature:r}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,o),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,o),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},cl=(s,e,t,n,r)=>{try{let o=nt({result_picker_used:t.toString(),...r?{signature:r}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,o),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,o),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},pl=(s,e,t,n,r,o)=>{try{let i=nt({...o?{signature:o}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(r,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},ho=(s,e,t,n)=>{try{let r=nt({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,r);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,r);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,r);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var xn=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"object":return"object";default:return"string"}})();return s?.isArray?`array of ${e}s`:e},be=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()}},dl=s=>{let t=s.map(n=>`'${n.title}' (${xn(n.type)})`).join(", ");return new be(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${s[0]?.title}:") and then provide a valid ${xn(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},fo=s=>new be(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${xn(s.type)} value directly after.`);var Ao=s=>new be(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${xn(s.type)}. Do not use null, undefined, or leave it blank.`),ml=(s,e)=>new be(`Invalid JSON: ${e} in field '${s.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),gl=(s,e)=>new be(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${xn(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),hl=(s,e,t)=>new be(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${xn(s.type)}. Ensure formatting exactly matches the expected type.`),fl=(s,e,t)=>new be(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Al=(s,e,t)=>new be(`Invalid date/time for '${s.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Ys=(s,e,t)=>new be(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),yn=(s,e,t,n)=>{let r=`Field '${s.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 be(r)},Qs=(s,e,t,n)=>{let r=`Field '${s.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 be(r)};var xl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";sa(s,e,l,n)}return r&&Vs(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},yl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";ia(s,e,l,n)}return r&&Vs(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},bl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&aa(s,e,n),r&&il(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};function Il(s,e){if(!e)return s;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 s;let n=t.join(". ");return!s||s.trim().length===0?n:`${s.trim().endsWith(".")?s.trim():`${s.trim()}.`} ${n}`}function bo(s,e="Schema"){if("name"in s&&"type"in s)return xo(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=xo(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function xo(s,e=!1){let t=s.type,n=Il(s.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: ${s.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.items.properties[o]=xo(a,!0),i.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=Il(t.description||s.description,t);r.items={type:Tl(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,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.properties[o]=xo(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Tl(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 Tl(s){switch(s){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 yo(s){if(!s||typeof s!="object")throw new Error("Schema must be an object");if(s.type==="array"){if(!s.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');yo(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))yo(e)}var _t=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},rr=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},Sc=(s,e=.1)=>{let t=[...s].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var tr=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:i}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(u=>u.index===i);if(!l){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let u=l.value.thought;l.value.thought=typeof u=="string"?u+r:r}if(Array.isArray(o)&&o.length>0){let u=l.value.thoughtBlocks??[];for(let c of o){let p=u.length>0?u[u.length-1]:void 0;!c.signature&&c.data?p&&!p.signature?(p.data=(p.data??"")+c.data,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):c.signature?p&&!p.signature?(p.data=(p.data??"")+c.data,p.signature=c.signature,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):u.length===0&&u.push(structuredClone(c))}l.value.thoughtBlocks=u,u.length>0&&(l.value.thought=u.map(c=>c.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(i=>i.index===e).map(i=>i.value):o=r.find(i=>i.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(i=>({...i,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},An=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new tr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new tr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ht(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Fr(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 tr):this.defaultMemory.reset()}};var ot=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()}},po=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new ot({message:o});if(!o)throw r?new ot({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Hs=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let r=s.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let i of r){let{message:a,fn:l}=i,u=await l(o,n);if(u!==void 0){if(typeof u=="string")throw new ot({message:u});if(!u&&a)throw new ot({message:a})}}};var Ks={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},nr,Ws=s=>{if(nr)return nr;let e=s??Z.meter;if(e)return nr=Oc(e),nr};var nl=()=>{let s=[];return Z.meter||s.push("Global meter not initialized"),!nr&&Z.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Oc=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),mo=Ks,rl=s=>{mo={...mo,...s}},ol=()=>({...mo}),nt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=mo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},sl=(s,e,t,n,r,o)=>{try{let i=nt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},go=(s,e,t,n)=>{try{let r=nt({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,r),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,r),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Vs=(s,e,t)=>{try{let n=nt({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},il=(s,e)=>{try{let t=nt({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},Js=(s,e,t,n,r)=>{try{let o=nt({success:t.toString(),...r?{signature:r}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,o),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,o),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,o),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},al=(s,e,t,n,r=!1,o)=>{try{let i=nt({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},ll=(s,e,t,n)=>{try{let r=nt({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,r),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},ul=(s,e,t,n,r)=>{try{let o=nt({is_streaming:e.toString(),...r?{signature:r}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,o),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,o),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},cl=(s,e,t,n,r)=>{try{let o=nt({result_picker_used:t.toString(),...r?{signature:r}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,o),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,o),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},pl=(s,e,t,n,r,o)=>{try{let i=nt({...o?{signature:o}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(r,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},ho=(s,e,t,n)=>{try{let r=nt({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,r);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,r);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,r);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var xn=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"object":return"object";default:return"string"}})();return s?.isArray?`array of ${e}s`:e},be=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()}},dl=s=>{let t=s.map(n=>`'${n.title}' (${xn(n.type)})`).join(", ");return new be(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${s[0]?.title}:") and then provide a valid ${xn(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},fo=s=>new be(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${xn(s.type)} value directly after.`);var Ao=s=>new be(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${xn(s.type)}. Do not use null, undefined, or leave it blank.`),ml=(s,e)=>new be(`Invalid JSON: ${e} in field '${s.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),gl=(s,e)=>new be(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${xn(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),hl=(s,e,t)=>new be(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${xn(s.type)}. Ensure formatting exactly matches the expected type.`),fl=(s,e,t)=>new be(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Al=(s,e,t)=>new be(`Invalid date/time for '${s.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),Ys=(s,e,t)=>new be(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),yn=(s,e,t,n)=>{let r=`Field '${s.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 be(r)},Qs=(s,e,t,n)=>{let r=`Field '${s.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 be(r)};var xl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";sa(s,e,l,n)}return r&&Vs(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},yl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";ia(s,e,l,n)}return r&&Vs(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},bl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&aa(s,e,n),r&&il(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};function Il(s,e){if(!e)return s;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 s;let n=t.join(". ");return!s||s.trim().length===0?n:`${s.trim().endsWith(".")?s.trim():`${s.trim()}.`} ${n}`}function bo(s,e="Schema"){if("name"in s&&"type"in s)return xo(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=xo(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function xo(s,e=!1){let t=s.type,n=Il(s.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: ${s.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.items.properties[o]=xo(a,!0),i.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=Il(t.description||s.description,t);r.items={type:Tl(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,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.properties[o]=xo(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Tl(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 Tl(s){switch(s){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 yo(s){if(!s||typeof s!="object")throw new Error("Schema must be an object");if(s.type==="array"){if(!s.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');yo(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))yo(e)}var _t=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},rr=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()}},or=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(`