@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 +4 -3
- package/index.cjs.map +1 -1
- package/index.global.js +4 -3
- package/index.global.js.map +1 -1
- package/index.js +4 -3
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.global.js
CHANGED
|
@@ -194,8 +194,8 @@ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } }
|
|
|
194
194
|
`)+A.title}:`,x=Nl(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&&i.length===1){t.inAssumedField=!0,t.currField=i[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(i[0])||t.extractedFields.push(i[0]),t.streamedIndex[i[0].name]===void 0&&(t.streamedIndex[i[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=i.find(A=>!A.isOptional);if(g)throw fo(g)}break}if(a&&p&&a.name!==p.name)throw fo(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=Ro(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)}},di=(s,e,t,n,r)=>{let o=r?.strictMode??!1,i=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=s.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=Ro(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=s.getOutputFields().find(d=>!d.isOptional);if(p)throw fo(p)}if(Fu(s,e,n,t),!i){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?ci(t,e,s.getOutputFields()):c||ci(t,e,s.getOutputFields())}},Fu=(s,e,t,n)=>{let r=s.getOutputFields();if(r.length===1){let i=r[0];if(i){let a=`${i.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
|
|
196
196
|
${i.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=Ro(i,d);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
|
|
197
|
-
`);for(let i of r){if(i.name in e)continue;let a=`${i.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=Ro(i,u);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},$l=(s,e,t=!1)=>{switch(s.type?.name){case"code":return ui(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.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(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Pl(s,e,t);case"datetime":return Fl(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*Ll(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[i]??0,p=u===0,d=(t<0?0:t)+u,m=s.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:{[i]:A}},r.streamedIndex[i]=u+g.length)}function*mi(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*Ll(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*Ll(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(u=>u.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let u=n.streamedIndex?.[i]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=c?c.length:1;else if(c){let u=n.streamedIndex[i];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=c.length}}}}function Ro(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Ao(s)}let t;if(s.type?.name==="json"&&!s.type?.isArray)try{let r=ui(e);return t=JSON.parse(r),t}catch(r){throw ml(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Dl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw gl(s,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let i=typeof o=="string"?o.trim():o;if(typeof i=="string"&&(s.type?.name==="object"||s.type?.name==="json"))try{let a=ui(i);i=JSON.parse(a)}catch{}t[r]=$l(s,i,!0)}}else t=$l(s,e)}catch(r){throw hl(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&wt(t,s),(n.name==="string"||n.name==="code")&&qe(t,s),n.name==="number"&&He(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?qe(r,s):n.name==="number"&&He(r,s));return t}function So(s,e){let
|
|
198
|
-
Content: ${i.content}`)}async function*Nu({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,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:T}){let I=h?void 0:Zs(t,s.functionCalls,s.values,n);if(I){if(!r)throw new Error("Functions are not defined");let E=await To({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...E]),s.functionCalls=[]}else{let E=e.getOutputFields(),C=e.hasComplexFields(),O=!1;if(C)try{let y=JSON.parse(s.content),k={};for(let F of Object.keys(y))E.some(P=>P.name===F)&&(k[F]=y[F]);So(e,k),Object.assign(s.values,k),yield{index:s.index,delta:k},O=!0}catch(y){let k=(y.message||"").toLowerCase();if(k.includes("at least")||k.includes("at most")||k.includes("must match pattern")||k.includes("invalid url")||k.includes("required")||k.includes("missing")||k.includes("valid email")||k.includes("number must be"))throw y}if(!O){let y=h!==void 0;di(e,s.values,s.xstate,s.content,{strictMode:c,treatAllFieldsOptional:y,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let y=await h.processResults(s.values);if(y&&y.length>0){if(!r)throw new Error("Functions are not defined");let k=await To({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...k]),o.updateResult({name:void 0,content:s.content,functionCalls:y.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}})),index:s.index},i);return}}await Hs(p,s.xstate,s.content,!0),await po(d,s.values),m.length&&await gi(m,s.values,o,i),g.length!==0&&await hi(g,s.content,s.xstate,o,s.values,i,!0),yield*mi(e,s.content,s.values,s.xstate,s.index)}}async function*Bl({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,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:T,disableMemoryCleanup:I}){let E=e.results??[],C=x!==void 0;t.addResponse(E,n);let O=[];for(let P of E)if(Array.isArray(P?.citations))for(let w of P.citations)w?.url&&O.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let P of E){let w=l[P.index];if(!w)throw new Error(`No state found for result (index: ${P.index})`);if(e.modelUsage){let v=Array.from(new Map(O.filter(S=>S.url).map(S=>[S.url,S])).values()),b={...e.modelUsage,...v.length?{citations:v}:{}};if(c.push(b),f&&h){let S=structuredClone(b);delete S.citations,h({name:"ChatResponseUsage",value:S}),b.citations&&b.citations.length>0&&h({name:"ChatResponseCitations",value:b.citations})}}if(x&&P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought),vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C});let b=(await x.processResults(w.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));b&&b.length>0&&t.updateResult({name:P.name,content:P.content,functionCalls:b,index:P.index},n)}if(P.functionCalls?.length){let v=Zs(s,P.functionCalls,w.values);if(v&&v.length>0){if(!o)throw new Error("Functions are not defined");let b;try{b=await To({ai:s,functionList:o,functionCalls:v,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:u,index:P.index,functionResultFormatter:A,logger:h,debug:f,stopFunctionNames:T})}catch(S){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),S}w.functionsExecuted=new Set([...w.functionsExecuted,...b])}}else if(P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought);let v=g.getOutputFields();if(g.hasComplexFields())try{let S=JSON.parse(P.content),R={};for(let M of Object.keys(S))v.some(_=>_.name===M)&&(R[M]=S[M]);So(g,R),Object.assign(w.values,R)}catch(S){if(S.name?.includes("ValidationError")||S.name?.includes("Error")){let R=(S.message||"").toLowerCase();if(R.includes("at least")||R.includes("at most")||R.includes("must match pattern")||R.includes("invalid url")||R.includes("required")||R.includes("missing")||R.includes("valid email")||R.includes("number must be"))throw S}vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C})}else vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C})}if(await po(p,w.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await gi(d,w.values,t,n),P.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
197
|
+
`);for(let i of r){if(i.name in e)continue;let a=`${i.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=Ro(i,u);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},$l=(s,e,t=!1)=>{switch(s.type?.name){case"code":return ui(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.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(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Pl(s,e,t);case"datetime":return Fl(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*Ll(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[i]??0,p=u===0,d=(t<0?0:t)+u,m=s.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:{[i]:A}},r.streamedIndex[i]=u+g.length)}function*mi(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:c}=i;yield*Ll(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*Ll(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(u=>u.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let u=n.streamedIndex?.[i]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=c?c.length:1;else if(c){let u=n.streamedIndex[i];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=c.length}}}}function Ro(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Ao(s)}let t;if(s.type?.name==="json"&&!s.type?.isArray)try{let r=ui(e);return t=JSON.parse(r),t}catch(r){throw ml(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Dl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw gl(s,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let i=typeof o=="string"?o.trim():o;if(typeof i=="string"&&(s.type?.name==="object"||s.type?.name==="json"))try{let a=ui(i);i=JSON.parse(a)}catch{}t[r]=$l(s,i,!0)}}else t=$l(s,e)}catch(r){throw hl(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&wt(t,s),(n.name==="string"||n.name==="code")&&qe(t,s),n.name==="number"&&He(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?qe(r,s):n.name==="number"&&He(r,s));return t}function So(s,e,t){let n=s.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw Ao(r);continue}let i=r.type;if(i){if(i.name==="url"&&wt(o,r),(i.name==="string"||i.name==="code")&&qe(o,r),i.name==="number"&&He(o,r),i.isArray&&Array.isArray(o))for(let a of o)a!=null&&(i.name==="url"?wt(a,r):i.name==="string"||i.name==="code"?qe(a,r):i.name==="number"&&He(a,r));if(i.name==="object"&&i.fields&&typeof o=="object"&&!Array.isArray(o)&&wo(r,o,t),i.isArray&&i.fields&&Array.isArray(o)&&i.name==="object")for(let a of o)a&&typeof a=="object"&&wo(r,a,t)}}}function wo(s,e,t){let n=s.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let i={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[i.name];if(a==null){if(!i.isOptional&&!t?.allowMissingRequired)throw Ao(i);continue}let l=i.type;if(l){if(l.name==="url"&&wt(a,i),(l.name==="string"||l.name==="code")&&qe(a,i),l.name==="number"&&He(a,i),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?wt(c,i):l.name==="string"||l.name==="code"?qe(c,i):l.name==="number"&&He(c,i));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&wo(i,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&wo(i,c,t)}}}var ui=s=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function gi(s,e,t,n){for(let r of s){if(e[r.field.name]===void 0)continue;let o=r.process,i=await o(e[r.field.name],{sessionId:n,values:e,done:!0});Gl(r.field,t,i,n)}}async function hi(s,e,t,n,r,o,i=!1){for(let a of s){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:i});Gl(t.currField,n,u,o)}}var Gl=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),o=_u(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function _u(s,e){let t=s.type?.name==="code",n=s.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*Ul({res:s,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,i,a=[],l=s.getReader();try{for(;;){let{done:c,value:u}=await l.read();if(c)break;let p=u;p.modelUsage&&(i=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*Du({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Nu({...r,state:c,debug:n});if(i){if(a.length){let c=Array.from(new Map(a.filter(u=>u.url).map(u=>[u.url,u])).values());i.citations=c}if(e.push(i),n&&r.logger){let c=structuredClone(i);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),i.citations&&i.citations.length>0&&r.logger({name:"ChatResponseCitations",value:i.citations})}}}async function*Du({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:i,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(s.functionCalls&&s.functionCalls.length>0)Er(i.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:i.functionCalls,thoughtBlock:s.thoughtBlock,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[c]:s.thought}}),i.content+=s.content,e.updateResult({name:s.name,content:i.content,thoughtBlock:s.thoughtBlock,delta:s.content,index:s.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let A=Rl(i.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]);So(a,h,{allowMissingRequired:!0}),Object.assign(i.values,h),yield{index:s.index,delta:h};return}}if(pi(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;u.length!==0&&await Hs(u,i.xstate,i.content),l.length!==0&&await hi(l,i.content,i.xstate,e,i.values,t),yield*mi(a,i.content,i.values,i.xstate,s.index),await po(p,i.values)}else s.thought&&s.thought.length>0?(i.values[c]=(i.values[c]??"")+s.thought,yield{index:s.index,delta:{[c]:s.thought}},e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thought:s.thought,thoughtBlock:s.thoughtBlock},t)):s.thoughtBlock&&e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thoughtBlock:s.thoughtBlock},t);if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
198
|
+
Content: ${i.content}`)}async function*Nu({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,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:T}){let I=h?void 0:Zs(t,s.functionCalls,s.values,n);if(I){if(!r)throw new Error("Functions are not defined");let E=await To({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...E]),s.functionCalls=[]}else{let E=e.getOutputFields(),C=e.hasComplexFields(),O=!1;if(C)try{let y=JSON.parse(s.content),k={};for(let F of Object.keys(y))E.some(P=>P.name===F)&&(k[F]=y[F]);So(e,k,{allowMissingRequired:!0}),Object.assign(s.values,k),yield{index:s.index,delta:k},O=!0}catch(y){let k=(y.message||"").toLowerCase();if(k.includes("at least")||k.includes("at most")||k.includes("must match pattern")||k.includes("invalid url")||k.includes("required")||k.includes("missing")||k.includes("valid email")||k.includes("number must be"))throw y}if(!O){let y=h!==void 0;di(e,s.values,s.xstate,s.content,{strictMode:c,treatAllFieldsOptional:y,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let y=await h.processResults(s.values);if(y&&y.length>0){if(!r)throw new Error("Functions are not defined");let k=await To({ai:t,functionList:r,functionCalls:y,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:u,functionResultFormatter:A,logger:f,debug:x,stopFunctionNames:T});s.functionsExecuted=new Set([...s.functionsExecuted,...k]),o.updateResult({name:void 0,content:s.content,functionCalls:y.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}})),index:s.index},i);return}}await Hs(p,s.xstate,s.content,!0),await po(d,s.values),m.length&&await gi(m,s.values,o,i),g.length!==0&&await hi(g,s.content,s.xstate,o,s.values,i,!0),yield*mi(e,s.content,s.values,s.xstate,s.index)}}async function*Bl({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,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:T,disableMemoryCleanup:I}){let E=e.results??[],C=x!==void 0;t.addResponse(E,n);let O=[];for(let P of E)if(Array.isArray(P?.citations))for(let w of P.citations)w?.url&&O.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let P of E){let w=l[P.index];if(!w)throw new Error(`No state found for result (index: ${P.index})`);if(e.modelUsage){let v=Array.from(new Map(O.filter(S=>S.url).map(S=>[S.url,S])).values()),b={...e.modelUsage,...v.length?{citations:v}:{}};if(c.push(b),f&&h){let S=structuredClone(b);delete S.citations,h({name:"ChatResponseUsage",value:S}),b.citations&&b.citations.length>0&&h({name:"ChatResponseCitations",value:b.citations})}}if(x&&P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought),vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C});let b=(await x.processResults(w.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));b&&b.length>0&&t.updateResult({name:P.name,content:P.content,functionCalls:b,index:P.index},n)}if(P.functionCalls?.length){let v=Zs(s,P.functionCalls,w.values);if(v&&v.length>0){if(!o)throw new Error("Functions are not defined");let b;try{b=await To({ai:s,functionList:o,functionCalls:v,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:u,index:P.index,functionResultFormatter:A,logger:h,debug:f,stopFunctionNames:T})}catch(S){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),S}w.functionsExecuted=new Set([...w.functionsExecuted,...b])}}else if(P.content){P.thought&&P.thought.length>0&&(w.values[m]=P.thought);let v=g.getOutputFields();if(g.hasComplexFields())try{let S=JSON.parse(P.content),R={};for(let M of Object.keys(S))v.some(_=>_.name===M)&&(R[M]=S[M]);So(g,R),Object.assign(w.values,R)}catch(S){if(S.name?.includes("ValidationError")||S.name?.includes("Error")){let R=(S.message||"").toLowerCase();if(R.includes("at least")||R.includes("at most")||R.includes("must match pattern")||R.includes("invalid url")||R.includes("required")||R.includes("missing")||R.includes("valid email")||R.includes("number must be"))throw S}vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C})}else vo(g,w.values,P.content,{strictMode:a,treatAllFieldsOptional:C})}if(await po(p,w.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await gi(d,w.values,t,n),P.finishReason==="length")throw new Error(`Max tokens reached before completion
|
|
199
199
|
Content: ${P.content}`)}let y=l.map(P=>P.values);for(let P of y)for(let w of g.getOutputFields())w.isInternal&&delete P[w.name];let k=g.getOutputFields(),F=y.map((P,w)=>{let v={};for(let b of k)b.isInternal||(v[b.name]=P[b.name]);return P[m]!==void 0&&(v[m]=P[m]),{index:w,delta:v}});for(let P of F)yield P}function jl(s,e,t,n){let r=s.getLast(n);if(!r)return!0;for(let[o,i]of t.entries()){let a=e?Array.from(e).some(p=>i.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 bn=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 K=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},fi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new K("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 K("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 K('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 K(`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 K)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new K(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new K(`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 K(`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 K(`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 K("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new K("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 K(`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 K?r:new K(`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 K(`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 K?r:new K(`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 K(`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 K(`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(),i=this.match("[]");n={name:o,isArray:i}}catch(o){throw o instanceof K?o:new K(`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 i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new K(`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 K(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new K(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new K(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new K(`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(i==="audio")throw new K(`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(i){throw i instanceof K?i:new K(`Output field "${e}": ${i instanceof Error?i.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(Z.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 i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new K(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new K(`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 K(`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 K(`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"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${o}${i}`;throw new K(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 K("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 K(`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 K(`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 i=this.input.slice(o,Math.min(this.position,o+20));throw new K(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${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 K(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function zl(s){return new fi(s).parse()}var ar=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,i])=>[o,Ai(i)])):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,i])=>[o,Ai(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new ge(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0),t}},xe=class s{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 s({...this,isOptional:!0})}array(e){return new s({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new s({...this,isInternal:!0})}min(e){return this.type==="string"?new s({...this,minLength:e}):this.type==="number"?new s({...this,minimum:e}):this}max(e){return this.type==="string"?new s({...this,maxLength:e}):this.type==="number"?new s({...this,maximum:e}):this}email(){return this.type==="string"?new s({...this,format:"email"}):this}url(){return this.type==="string"?new s({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new s({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new s({...this,format:"date"}):this}datetime(){return this.type==="string"?new s({...this,format:"date-time"}):this}},ie=Object.assign(()=>new ar,{string:s=>new xe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new xe({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new xe({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new xe({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new xe({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new xe({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new xe({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new xe({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new xe({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new xe({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new xe({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),email:s=>new xe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,format:"email"}),code:(s,e)=>new xe({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1}),object:(s,e)=>new xe({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1})});function Ai(s){return{type:s.type,isArray:s.isArray,options:s.options,description:s.description,isOptional:s.isOptional,isInternal:s.isInternal,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format,fields:s.fields?Object.fromEntries(Object.entries(s.fields).map(([e,t])=>[e,Ai(t)])):void 0}}function ko(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var B=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ge=class s{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=zl(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 B(`Invalid Signature: ${n.message}`,void 0,r)}throw new B(`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 s)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 B("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 B("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 B?t:new B(`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 B("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 s(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new B("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 B("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 B("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);st(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);st(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new B(`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 B(`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 B?t:new B(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new B("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 st(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof B?t:new B(`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 s(this);return n.addInputField({name:e,...ko(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...ko(t)},o=n.parseField(r);st(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new B(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===o.name)throw new B(`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 s(this);return n.addOutputField({name:e,...ko(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...ko(t)},o=n.parseField(r);st(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new B(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===o.name)throw new B(`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=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.sigHash=Be("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{st(e,"input")}),this.getOutputFields().forEach(e=>{st(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Be("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Hl(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof B?e:new B(`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 B(`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 B(`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 B(`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 B("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new B("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 bo(e,this.description??"Schema")}};function ql(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function Hl(s,e,t){let n=s?`"${s}" `:"",r=e.map(ql).join(", "),o=t.map(ql).join(", ");return`${n}${r} -> ${o}`}function $u(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function st(s,e){if(!s.name||s.name.length===0)throw new B("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!$u(s.name))throw new B(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(Z.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new B(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new B(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new B(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Lu(s,e)}function Lu(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new B(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new B("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new B("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new B("Empty class option found",s.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new B(`Invalid class option "${o}"`,s.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 B("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new B("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new B("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&xi(t.fields,s.name,e)}function xi(s,e,t,n=1){for(let[r,o]of Object.entries(s)){let i=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new B(`${o.type} type is not allowed in nested object fields`,i,`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&&xi(o.fields,i,t,n+1),o.isArray&&o.fields&&xi(o.fields,`${i}[]`,t,n+1)}}var vt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ge(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new bn,this.key={id:this.signature.hash()}}getSignature(){return new ge(this.signature)}setSignature(e){this.signature=new ge(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of o){let c=i[l.name];c!==void 0&&(Co(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 ir(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 Kl=`
|
|
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&&
|
|
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,i,{...n,isInputField:!0})).filter(u=>u!==void 0).flat(),l=this.sig.getOutputFields().map(u=>this.renderInField(u,i,{...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},i=this.sig.hasComplexFields();for(let a of e){if(i){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
|