@ax-llm/ax 15.0.7 → 15.0.8

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 CHANGED
@@ -194,8 +194,8 @@ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } }
194
194
  `)+A.title}:`,x=$a(n,f,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=f.length,u=g,p=A)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(A=>!A.isOptional);if(g)throw zr(g)}break}if(a&&p&&a.name!==p.name)throw zr(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),A=Xr(t.currField,g);A!==void 0&&(e[t.currField.name]=A),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,p!==void 0&&u!==void 0&&(t.currField=p,t.currFieldIndex=u),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Fs=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=i.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let g=`
195
195
  ${m.title}:`,A=n.indexOf(g,t.s);A!==-1&&A<c&&(c=A)}let p=n.substring(t.s,c).trim(),d=Xr(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw zr(p)}if(gc(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Ms(t,e,i.getOutputFields()):c||Ms(t,e,i.getOutputFields())}},gc=(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}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=Xr(s,d);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 p=Xr(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},La=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Es(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 Fa(i,e,t);case"datetime":return _a(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*Ga(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let A=p?g.trimStart():g;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+g.length)}function*_s(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*Ga(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*Ga(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function Xr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw Hr(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=Es(e);return t=JSON.parse(r),t}catch(r){throw xa(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Da(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ya(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=Es(s);s=JSON.parse(a)}catch{}t[r]=La(i,s,!0)}}else t=La(i,e)}catch(r){throw ba(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&ut(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 to(i,e){let t=i.getOutputFields();for(let n of t){let r=e[n.name];if(r==null){if(!n.isOptional)throw Hr(n);continue}let o=n.type;if(o){if(o.name==="url"&&ut(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"?ut(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"&&!Array.isArray(r)&&Zr(n,r),o.isArray&&o.fields&&Array.isArray(r)&&o.name==="object")for(let s of r)s&&typeof s=="object"&&Zr(n,s)}}}function Zr(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 Hr(o);continue}let a=o.type;if(a){if(a.name==="url"&&ut(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"?ut(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)&&Zr(o,s),a.isArray&&a.fields&&Array.isArray(s)&&a.name==="object")for(let l of s)l&&typeof l=="object"&&Zr(o,l)}}}var Es=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Ns(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 Ds(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=hc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function hc(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 p=u;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&!d.thoughtBlock&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*fc({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Ac({...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*fc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)sr(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 d=a.getOutputFields();if(a.hasComplexFields()){let A=Oa(s.content);if(A&&typeof A=="object"){let h={};for(let f of Object.keys(A))d.some(x=>x.name===f)&&(h[f]=A[f]);to(a,h),Object.assign(s.values,h),yield{index:i.index,delta:h};return}}if(Ps(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await bs(u,s.xstate,s.content),l.length!==0&&await Ds(l,s.content,s.xstate,e,s.values,t),yield*_s(a,s.content,s.values,s.xstate,i.index),await Ur(p,s.values)}else i.thought&&i.thought.length>0?(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,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
- Content: ${s.content}`)}async function*Ac({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:A,signatureToolCallingManager:h,logger:f,debug:x,stopFunctionNames:I}){let y=h?void 0:vs(t,i.functionCalls,i.values,n);if(y){if(!r)throw new Error("Functions are not defined");let S=await Qr({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:I});i.functionsExecuted=new Set([...i.functionsExecuted,...S]),i.functionCalls=[]}else{let S=e.getOutputFields(),T=e.hasComplexFields(),w=!1;if(T)try{let b=JSON.parse(i.content),k={};for(let E of Object.keys(b))S.some(M=>M.name===E)&&(k[E]=b[E]);to(e,k),Object.assign(i.values,k),yield{index:i.index,delta:k},w=!0}catch(b){let k=(b.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 b}if(!w){let b=h!==void 0;Fs(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:b,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let b=await h.processResults(i.values);if(b&&b.length>0){if(!r)throw new Error("Functions are not defined");let k=await Qr({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:I});i.functionsExecuted=new Set([...i.functionsExecuted,...k]),o.updateResult({name:void 0,content:i.content,functionCalls:b.map(E=>({id:E.id,type:"function",function:{name:E.name,params:E.args}})),index:i.index},s);return}}await bs(p,i.xstate,i.content,!0),await Ur(d,i.values),m.length&&await Ns(m,i.values,o,s),g.length!==0&&await Ds(g,i.content,i.xstate,o,i.values,s,!0),yield*_s(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:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:A,logger:h,debug:f,signatureToolCallingManager:x,stopFunctionNames:I,disableMemoryCleanup:y}){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 _=Array.from(new Map(w.filter(v=>v.url).map(v=>[v.url,v])).values()),C={...e.modelUsage,..._.length?{citations:_}:{}};if(c.push(C),f&&h){let v=structuredClone(C);delete v.citations,h({name:"ChatResponseUsage",value:v}),C.citations&&C.citations.length>0&&h({name:"ChatResponseCitations",value:C.citations})}}if(x&&M.content){M.thought&&M.thought.length>0&&(R.values[m]=M.thought),eo(g,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 _=vs(i,M.functionCalls,R.values);if(_&&_.length>0){if(!o)throw new Error("Functions are not defined");let C;try{C=await Qr({ai:i,functionList:o,functionCalls:_,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:u,index:M.index,functionResultFormatter:A,logger:h,debug:f,stopFunctionNames:I})}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 _=g.getOutputFields();if(g.hasComplexFields())try{let v=JSON.parse(M.content),O={};for(let D of Object.keys(v))_.some(W=>W.name===D)&&(O[D]=v[D]);to(g,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}eo(g,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}else eo(g,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}if(await Ur(p,R.values),y||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Ns(d,R.values,t,n),M.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 p=Xr(s,u);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},La=(i,e,t=!1)=>{switch(i.type?.name){case"code":return Es(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 Fa(i,e,t);case"datetime":return _a(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*Ga(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[s]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let A=p?g.trimStart():g;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+g.length)}function*_s(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*Ga(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*Ga(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(u=>u.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let u=n.streamedIndex?.[s]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=c?c.length:1;else if(c){let u=n.streamedIndex[s];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c.length}}}}function Xr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw Hr(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=Es(e);return t=JSON.parse(r),t}catch(r){throw xa(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Da(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ya(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=Es(s);s=JSON.parse(a)}catch{}t[r]=La(i,s,!0)}}else t=La(i,e)}catch(r){throw ba(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&ut(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 to(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw Hr(r);continue}let s=r.type;if(s){if(s.name==="url"&&ut(o,r),(s.name==="string"||s.name==="code")&&_e(o,r),s.name==="number"&&Ne(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?ut(a,r):s.name==="string"||s.name==="code"?_e(a,r):s.name==="number"&&Ne(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&Zr(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&Zr(r,a,t)}}}function Zr(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw Hr(s);continue}let l=s.type;if(l){if(l.name==="url"&&ut(a,s),(l.name==="string"||l.name==="code")&&_e(a,s),l.name==="number"&&Ne(a,s),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?ut(c,s):l.name==="string"||l.name==="code"?_e(c,s):l.name==="number"&&Ne(c,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Zr(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&Zr(s,c,t)}}}var Es=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Ns(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 Ds(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=hc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function hc(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 p=u;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&!d.thoughtBlock&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*fc({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Ac({...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*fc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)sr(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 d=a.getOutputFields();if(a.hasComplexFields()){let A=Oa(s.content);if(A&&typeof A=="object"){let h={};for(let f of Object.keys(A))d.some(x=>x.name===f)&&(h[f]=A[f]);to(a,h,{allowMissingRequired:!0}),Object.assign(s.values,h),yield{index:i.index,delta:h};return}}if(Ps(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await bs(u,s.xstate,s.content),l.length!==0&&await Ds(l,s.content,s.xstate,e,s.values,t),yield*_s(a,s.content,s.values,s.xstate,i.index),await Ur(p,s.values)}else i.thought&&i.thought.length>0?(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,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
+ Content: ${s.content}`)}async function*Ac({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:A,signatureToolCallingManager:h,logger:f,debug:x,stopFunctionNames:I}){let y=h?void 0:vs(t,i.functionCalls,i.values,n);if(y){if(!r)throw new Error("Functions are not defined");let S=await Qr({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:I});i.functionsExecuted=new Set([...i.functionsExecuted,...S]),i.functionCalls=[]}else{let S=e.getOutputFields(),T=e.hasComplexFields(),w=!1;if(T)try{let b=JSON.parse(i.content),k={};for(let E of Object.keys(b))S.some(M=>M.name===E)&&(k[E]=b[E]);to(e,k,{allowMissingRequired:!0}),Object.assign(i.values,k),yield{index:i.index,delta:k},w=!0}catch(b){let k=(b.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 b}if(!w){let b=h!==void 0;Fs(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:b,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let b=await h.processResults(i.values);if(b&&b.length>0){if(!r)throw new Error("Functions are not defined");let k=await Qr({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:I});i.functionsExecuted=new Set([...i.functionsExecuted,...k]),o.updateResult({name:void 0,content:i.content,functionCalls:b.map(E=>({id:E.id,type:"function",function:{name:E.name,params:E.args}})),index:i.index},s);return}}await bs(p,i.xstate,i.content,!0),await Ur(d,i.values),m.length&&await Ns(m,i.values,o,s),g.length!==0&&await Ds(g,i.content,i.xstate,o,i.values,s,!0),yield*_s(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:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:A,logger:h,debug:f,signatureToolCallingManager:x,stopFunctionNames:I,disableMemoryCleanup:y}){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 _=Array.from(new Map(w.filter(v=>v.url).map(v=>[v.url,v])).values()),C={...e.modelUsage,..._.length?{citations:_}:{}};if(c.push(C),f&&h){let v=structuredClone(C);delete v.citations,h({name:"ChatResponseUsage",value:v}),C.citations&&C.citations.length>0&&h({name:"ChatResponseCitations",value:C.citations})}}if(x&&M.content){M.thought&&M.thought.length>0&&(R.values[m]=M.thought),eo(g,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 _=vs(i,M.functionCalls,R.values);if(_&&_.length>0){if(!o)throw new Error("Functions are not defined");let C;try{C=await Qr({ai:i,functionList:o,functionCalls:_,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:u,index:M.index,functionResultFormatter:A,logger:h,debug:f,stopFunctionNames:I})}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 _=g.getOutputFields();if(g.hasComplexFields())try{let v=JSON.parse(M.content),O={};for(let D of Object.keys(v))_.some(W=>W.name===D)&&(O[D]=v[D]);to(g,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}eo(g,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}else eo(g,R.values,M.content,{strictMode:a,treatAllFieldsOptional:T})}if(await Ur(p,R.values),y||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Ns(d,R.values,t,n),M.finishReason==="length")throw new Error(`Max tokens reached before completion
199
199
  Content: ${M.content}`)}let b=l.map(M=>M.values);for(let M of b)for(let R of g.getOutputFields())R.isInternal&&delete M[R.name];let k=g.getOutputFields(),E=b.map((M,R)=>{let _={};for(let C of k)C.isInternal||(_[C.name]=M[C.name]);return M[m]!==void 0&&(_[m]=M[m]),{index:R,delta:_}});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(p=>s.functionsExecuted.has(p)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",u=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var nn=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"}},$s=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
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(J.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 $s(i).parse()}var Bn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ls(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,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Ls(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new ue(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0),t}},ge=class i{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}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 Bn,{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 Ls(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,Ls(t)])):void 0}}function no(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"}},ue=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,...no(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...no(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,...no(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...no(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"')}_forceComplexFields=!1;hasComplexFields=()=>{if(this._forceComplexFields)return!0;let e=t=>t.some(n=>n.type?.name==="object"||n.type?.isArray&&n.type.fields!==void 0);return e(this.inputFields)||e(this.outputFields)};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 Vr(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 xc(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(!xc(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(J.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&&yc(i,e)}function yc(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&&Gs(t.fields,i.name,e)}function Gs(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&&Gs(o.fields,s,t,n+1),o.isArray&&o.fields&&Gs(o.fields,`${s}[]`,t,n+1)}}var pt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ue(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 nn,this.key={id:this.signature.hash()}}getSignature(){return new ue(this.signature)}setSignature(e){this.signature=new ue(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&&(Yr(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 Un(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 Wa=`
201
201
  ## Function Call Instructions
@@ -251,7 +251,8 @@ ${m}
251
251
  \`\`\`
252
252
  `}];o>0&&g.length>0&&g[0]?.type==="text"&&t.push({type:"text",text:`---
253
253
 
254
- `}),g.forEach(A=>{A&&t.push(A)});continue}let a=this.sig.getInputFields().map(u=>this.renderInField(u,s,{...n,isInputField:!0})).filter(u=>u!==void 0).flat(),l=this.sig.getOutputFields().map(u=>this.renderInField(u,s,{...n,isInputField:!1})).filter(u=>u!==void 0).flat(),c=[...a,...l];o>0&&c.length>0&&c[0]?.type==="text"&&t.push({type:"text",text:`---
254
+ `}),g.forEach(A=>{A&&("text"in A&&(A.text=`${A.text}
255
+ `),t.push(A))});continue}let a=this.sig.getInputFields().map(u=>this.renderInField(u,s,{...n,isInputField:!0})).filter(u=>u!==void 0).flat(),l=this.sig.getOutputFields().map(u=>this.renderInField(u,s,{...n,isInputField:!1})).filter(u=>u!==void 0).flat(),c=[...a,...l];o>0&&c.length>0&&c[0]?.type==="text"&&t.push({type:"text",text:`---
255
256
 
256
257
  `}),c.forEach(u=>{"text"in u&&(u.text=`${u.text}
257
258
  `),t.push(u)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),r=this.sig.getOutputFields(),o={isExample:!0},s=this.sig.hasComplexFields();for(let a of e){if(s){let p=n.map(A=>this.renderInField(A,a,{...o,isInputField:!0})).filter(A=>A!==void 0).flat(),d={};for(let A of r)A.name in a&&(d[A.name]=a[A.name]);let m=JSON.stringify(d,null,2);[...p,{type:"text",text:`\`\`\`json