@ax-llm/ax 18.0.11 → 18.0.12
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 +2 -2
- package/index.cjs.map +1 -1
- package/index.global.js +2 -2
- package/index.global.js.map +1 -1
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/ax-agent.md +1 -1
- package/skills/ax-llm.md +1 -1
package/index.cjs
CHANGED
|
@@ -782,14 +782,14 @@ ${e.output}${e.actorFieldsOutput}`).join(`
|
|
|
782
782
|
}).join('\\n') || '(no user variables)';
|
|
783
783
|
})()`}var Cu=50,Lp=5e3,$p=8,Tu=10,Gp=2,Pr=class i{ai;program;actorProgram;responderProgram;functions;agents;debug;options;rlmConfig;runtime;actorFieldNames;sharedFieldNames;excludedSharedFields;actorDescription;responderDescription;recursionForwardOptions;actorForwardOptions;responderForwardOptions;activeAbortControllers=new Set;_stopRequested=!1;func;_parentSharedFields=new Set;constructor({ai:e,agentIdentity:t,signature:n,agents:r,functions:o},s){let{debug:a,contextFields:l,runtime:u,maxLlmCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,trajectoryPruning:g,contextManagement:h,actorFields:f,actorCallback:y,mode:x,recursionOptions:A,actorOptions:w,responderOptions:I}=s;this.ai=e,this.agents=r,this.functions=o,this.debug=a,this.options=s,this.runtime=u??new jt,this.rlmConfig={contextFields:l,sharedFields:s.sharedFields,runtime:this.runtime,maxLlmCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,trajectoryPruning:g,contextManagement:h,actorFields:f,actorCallback:y,mode:x},this.recursionForwardOptions=A;let{description:T,...S}=w??{},{description:_,...P}=I??{};this.actorDescription=T,this.actorForwardOptions=S,this.responderDescription=_,this.responderForwardOptions=P,this.program=new we(n,{...s});for(let G of r??[]){let F=G.getFunction().name;this.program.register(G,F)}t&&(this.func={name:qp(t.name),description:t.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let $=this.program.getSignature().getInputFields();for(let G of l)if(!$.some(F=>F.name===G))throw new Error(`RLM contextField "${G}" not found in signature`);if(this.program.getSignature().getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let U=this.program.getSignature().getOutputFields(),K=f??[];this.actorFieldNames=K;for(let G of K)if(!U.some(F=>F.name===G))throw new Error(`RLM actorField "${G}" not found in output signature`);let O=s.sharedFields??[];this.sharedFieldNames=O;for(let G of O)if(!$.some(F=>F.name===G))throw new Error(`sharedField "${G}" not found in signature input fields`);if(this.excludedSharedFields=s.excludeSharedFields??[],O.length>0&&r){let G=$.filter(F=>O.includes(F.name));for(let F of r){if(!(F instanceof i))continue;let J=new Set(F.getExcludedSharedFields()),M=G.filter(D=>!J.has(D.name));M.length!==0&&F._extendForSharedFields(M,l)}}this._buildSplitPrograms(),this.program.register(this.actorProgram,"actor"),this.program.register(this.responderProgram,"responder")}_buildSplitPrograms(){let e=this.program.getSignature().getInputFields(),t=this.rlmConfig.contextFields,n=this.sharedFieldNames,r=e.filter(x=>t.includes(x.name)),o=e.filter(x=>!t.includes(x.name)&&!n.includes(x.name)),s=this.program.getSignature().getOutputFields(),a=s.filter(x=>this.actorFieldNames.includes(x.name)),l=s.filter(x=>!this.actorFieldNames.includes(x.name)),u=he().addInputFields(o).input("contextMetadata",he.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",he.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",he.code("JavaScript code to execute in runtime session"));a.length>0&&(u=u.addOutputFields(a));let c=u.build(),p=he().addInputFields(o).input("contextData",he.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),d=this.rlmConfig.maxLlmCalls??Cu,m=this.rlmConfig.maxTurns??Tu,g=this.agents?.map(x=>{let A=x.getFunction();return{name:A.name,description:A.description,parameters:A.parameters}})??[],h=this.collectFunctions().map(x=>({name:x.name,description:x.description,parameters:x.parameters})),f=us(this.actorDescription,r,l,{runtimeUsageInstructions:this.runtime.getUsageInstructions(),maxLlmCalls:d,maxTurns:m,hasInspectRuntime:!!this.rlmConfig.contextManagement?.stateInspection,agents:g,functions:h}),y=cs(this.responderDescription,r);this.actorProgram=new we(c,{...this.options,description:f}),this.responderProgram=new we(p,{...this.options,description:y})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let s of e)r.some(a=>a.name===s.name)||(this._parentSharedFields.add(s.name),n.addInputField(s),o=!0);o&&this.program.setSignature(n);for(let s of e)t.includes(s.name)&&!this.rlmConfig.contextFields.includes(s.name)&&this.rlmConfig.contextFields.push(s.name);this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}collectFunctions(){let e=[];if(this.functions)for(let t of this.functions)typeof t=="object"&&"func"in t&&e.push(t);return e}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){if(!this.func)throw new Error("getFunction() requires agentIdentity to be set in the constructor");let e=this.forward.bind(this);return{...this.func,func:async(r,o)=>{let s=this.ai??o?.ai;if(!s)throw new Error("AI service is required to run the agent");let a=await e(s,r,o),u=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=u.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
|
|
784
784
|
`)}}}getExcludedSharedFields(){return this.excludedSharedFields}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r){let o=this.rlmConfig,s=this.runtime,a=n?.debug??this.debug??e?.getOptions()?.debug??!1,l={},u={},c;Array.isArray(t)?c=t.filter(v=>v.role==="user").reduce((v,j)=>({...v,...j.values}),{}):c=t;let p=this.sharedFieldNames;for(let[v,j]of Object.entries(c))o.contextFields.includes(v)?l[v]=j:p.includes(v)||(u[v]=j);let d={};for(let v of p)v in c&&(d[v]=c[v]),v in l&&(d[v]=l[v]);for(let v of o.contextFields)if(!(v in l))throw new Error(`RLM contextField "${v}" is missing from input values`);let m=o.maxLlmCalls??Cu,g=o.maxRuntimeChars??Lp,h=Math.max(1,o.maxBatchedLlmQueryConcurrency??$p),f=o.maxTurns??Tu,y=0,x=Math.floor(m*.8),A=this.recursionForwardOptions?.maxDepth??Gp,w=Math.max(0,A),{maxDepth:I,...T}=this.recursionForwardOptions??{},{functions:S,description:_,mem:P,sessionId:$,...U}=n??{},K={...this.recursionForwardOptions??{},maxDepth:Math.max(0,w-1)},O=["context"],G=he().input("task",he.string("Task for recursive analysis")).input("context",he.json("Optional context for the recursive task")).output("answer",he.string("Answer from recursive analysis")).build(),J=(o.mode??"simple")==="advanced"&&(K.maxDepth??0)>0?"advanced":"simple",M;w>0&&(J==="advanced"?M=new i({signature:G,agents:this.agents,functions:this.functions},{debug:a,...o,contextFields:O,actorFields:void 0,recursionOptions:K,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):M=new we(G,K));let D=v=>{if(v==null)return"";if(typeof v=="string")return It(v,g);try{return It(JSON.stringify(v),g)}catch{return It(String(v),g)}},Y=async(v,j)=>{if(!Array.isArray(v)&&typeof v=="object"&&v!==null&&"query"in v)return Y(v.query,v.context??j);if(r?.aborted)throw new Oe("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(v))return Bp(v,h,async le=>{try{return await Y(le.query,le.context)}catch(oe){if(oe instanceof Oe)throw oe;return`[ERROR] ${oe instanceof Error?oe.message:String(oe)}`}});let ie=await(async(le,oe)=>{let V=oe===void 0?void 0:typeof oe=="string"?It(oe,g):oe;if(y++,y>m)return`[ERROR] Sub-query budget exhausted (${m}/${m}). Use the data you have already accumulated to produce your final answer.`;if(w<=0||!M)return`[ERROR] Recursion depth limit reached (${A}).`;let W=3,ee;for(let fe=0;fe<W;fe++)try{let ue=await M.forward(e,{task:le,...V!==void 0?{context:V}:J==="advanced"?{context:""}:{}},{...U,...T,abortSignal:r,debug:a});return D(ue.answer)}catch(ue){if(ee=ue,!Dp(ue)||fe>=W-1)throw ue;let xe=Math.min(6e4,1e3*Math.pow(2,fe));await new Promise((st,mt)=>{let $e=!1,Ke,it=()=>{r&&Ke&&r.removeEventListener("abort",Ke)},ht=setTimeout(()=>{$e||($e=!0,it(),st())},xe);if(r){if(Ke=()=>{$e||($e=!0,clearTimeout(ht),it(),mt(new Oe("rlm-llm-query-retry-backoff",r.reason?String(r.reason):"Aborted during retry backoff")))},r.aborted){Ke();return}r.addEventListener("abort",Ke,{once:!0})}})}throw ee})(v,j);return y===x?`${ie}
|
|
785
|
-
[WARNING] ${y}/${m} sub-queries used. Plan to wrap up soon.`:ie},N=this.buildRuntimeGlobals(r,d),X,Ae=(v,j)=>{if(j.length===0)throw new Error(`${v}() requires at least one argument`);X={type:v,args:j}},ae=(...v)=>Ae("final",v),se=(...v)=>Ae("ask_clarification",v),re=["llmQuery","agents","final","ask_clarification",...o.contextManagement?.stateInspection?["inspect_runtime"]:[],...o.contextFields,...Object.keys(N)],Ie=o.contextManagement?.stateInspection?async()=>{try{let v=Iu(re),j=await Ce.execute(v,{signal:r,reservedNames:re});return typeof j=="string"?j:String(j)}catch(v){return`[inspect_runtime error: ${v instanceof Error?v.message:String(v)}]`}}:void 0,Le=()=>s.createSession({...l,llmQuery:Y,final:ae,ask_clarification:se,...Ie?{inspect_runtime:Ie}:{},...N}),ge="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",Ce=Le(),je=!1,Fe=v=>v instanceof Error&&v.message==="Session is closed",Me=v=>v instanceof Error&&v.message==="Execution timed out",C=v=>{if(v===void 0)return"(no output)";if(typeof v=="string")return It(v||"(no output)",g);try{return It(JSON.stringify(v,null,2),g)}catch{return It(String(v),g)}},k=v=>{let j=v,te=j?.name??"Error",ne=j?.message??String(v),ie=[`${te}: ${ne}`];if(j?.data!==void 0)try{ie.push(`Data: ${JSON.stringify(j.data,null,2)}`)}catch{ie.push(`Data: ${String(j.data)}`)}if(j?.cause!==void 0){let le=(oe,V)=>{if(V>4)return"[cause chain truncated]";let W=oe,ee=W?.name??"Error",fe=W?.message??String(oe),ue=[`${ee}: ${fe}`];if(W?.data!==void 0)try{ue.push(`Data: ${JSON.stringify(W.data,null,2)}`)}catch{ue.push(`Data: ${String(W.data)}`)}return W?.cause!==void 0&&ue.push(`Caused by: ${le(W.cause,V+1)}`),ue.join(`
|
|
785
|
+
[WARNING] ${y}/${m} sub-queries used. Plan to wrap up soon.`:ie},N=this.buildRuntimeGlobals(r,d,e),X,Ae=(v,j)=>{if(j.length===0)throw new Error(`${v}() requires at least one argument`);X={type:v,args:j}},ae=(...v)=>Ae("final",v),se=(...v)=>Ae("ask_clarification",v),re=["llmQuery","agents","final","ask_clarification",...o.contextManagement?.stateInspection?["inspect_runtime"]:[],...o.contextFields,...Object.keys(N)],Ie=o.contextManagement?.stateInspection?async()=>{try{let v=Iu(re),j=await Ce.execute(v,{signal:r,reservedNames:re});return typeof j=="string"?j:String(j)}catch(v){return`[inspect_runtime error: ${v instanceof Error?v.message:String(v)}]`}}:void 0,Le=()=>s.createSession({...l,llmQuery:Y,final:ae,ask_clarification:se,...Ie?{inspect_runtime:Ie}:{},...N}),ge="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",Ce=Le(),je=!1,Fe=v=>v instanceof Error&&v.message==="Session is closed",Me=v=>v instanceof Error&&v.message==="Execution timed out",C=v=>{if(v===void 0)return"(no output)";if(typeof v=="string")return It(v||"(no output)",g);try{return It(JSON.stringify(v,null,2),g)}catch{return It(String(v),g)}},k=v=>{let j=v,te=j?.name??"Error",ne=j?.message??String(v),ie=[`${te}: ${ne}`];if(j?.data!==void 0)try{ie.push(`Data: ${JSON.stringify(j.data,null,2)}`)}catch{ie.push(`Data: ${String(j.data)}`)}if(j?.cause!==void 0){let le=(oe,V)=>{if(V>4)return"[cause chain truncated]";let W=oe,ee=W?.name??"Error",fe=W?.message??String(oe),ue=[`${ee}: ${fe}`];if(W?.data!==void 0)try{ue.push(`Data: ${JSON.stringify(W.data,null,2)}`)}catch{ue.push(`Data: ${String(W.data)}`)}return W?.cause!==void 0&&ue.push(`Caused by: ${le(W.cause,V+1)}`),ue.join(`
|
|
786
786
|
`)};ie.push(`Caused by: ${le(j.cause,1)}`)}return It(ie.join(`
|
|
787
787
|
`),g)},R=async v=>{try{let j=await Ce.execute(v,{signal:r,reservedNames:re});return{output:C(j),isError:!1}}catch(j){if(r?.aborted)throw new Oe("rlm-session",r.reason??"Aborted");if(j instanceof Error&&(j.name==="AbortError"||j.message.startsWith("Aborted")))throw j;if(Me(j)&&(je=!0),Fe(j)){if(!je)return{output:k(j),isError:!0};try{je=!1,Ce=Le(),X=void 0;let te=await Ce.execute(v,{signal:r,reservedNames:re});return{output:It(`${ge}
|
|
788
788
|
${C(te)}`,g),isError:!1}}catch(te){return Me(te)&&(je=!0),{output:It(`${ge}
|
|
789
789
|
${k(te)}`,g),isError:!0}}}if(Me(j))return{output:k(j),isError:!0};throw j}},b=Up(l)||"(none)",E=o.contextManagement,B={errorPruning:E?.errorPruning??o.trajectoryPruning??!1,hindsightEvaluation:E?.hindsightEvaluation??!1,tombstoning:E?.tombstoning,pruneRank:E?.pruneRank??2},L=[],Q={...this.options,...this.actorForwardOptions,...n,debug:a,abortSignal:r},q={},H=E?.stateInspection?.contextThreshold;try{for(let v=0;v<f;v++){let j=ps(L)||"(no actions yet)";H&&j.length>H&&(j+="\n\n[HINT: Action log is large. Call `const state = await inspect_runtime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let te=await this.actorProgram.forward(e,{...u,contextMetadata:b,actionLog:j},Q);v===0&&(Q.debugHideSystemPrompt=!0),o.actorCallback&&await o.actorCallback(te);for(let W of this.actorFieldNames)W in te&&(q[W]=te[W]);let ne=te.javascriptCode,ie=ne?.trim();if(!ne||!ie)break;ne=ie;let le="";if(this.actorFieldNames.length>0){let W=this.actorFieldNames.filter(ee=>ee in te).map(ee=>`${ee}: ${te[ee]}`).join(`
|
|
790
790
|
`);W&&(le=`
|
|
791
791
|
Actor fields:
|
|
792
|
-
${W}`)}X=void 0;let{output:oe,isError:V}=await R(ne);if(L.push({turn:v+1,code:ne,output:oe,actorFieldsOutput:le,tags:V?["error"]:[]}),await bu(L,L.length-1,B,e),X)break}}finally{try{Ce.close()}catch{}}let z=X??{type:"final",args:[ps(L)||"(no actions were taken)"]};return{nonContextValues:u,contextMetadata:b,actionLog:ps(L),actorResult:z,actorFieldValues:q}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=wt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let s=this.ai??e,a=n?.debug??this.debug??s?.getOptions()?.debug??!1,{nonContextValues:l,actorResult:u,actorFieldValues:c}=await this._runActorLoop(s,t,n,o),p={...this.options,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};return{...await this.responderProgram.forward(s,{...l,contextData:u},p),...c}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async*streamingForward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=wt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let s=this.ai??e,a=n?.debug??this.debug??s?.getOptions()?.debug??!1,{nonContextValues:l,contextMetadata:u,actorResult:c,actorFieldValues:p}=await this._runActorLoop(s,t,n,o),d={...this.options,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};for await(let m of this.responderProgram.streamingForward(s,{...l,contextMetadata:u,actorResult:c},d))yield m;Object.keys(p).length>0&&(yield{version:1,index:0,delta:p})}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t){return async(...
|
|
792
|
+
${W}`)}X=void 0;let{output:oe,isError:V}=await R(ne);if(L.push({turn:v+1,code:ne,output:oe,actorFieldsOutput:le,tags:V?["error"]:[]}),await bu(L,L.length-1,B,e),X)break}}finally{try{Ce.close()}catch{}}let z=X??{type:"final",args:[ps(L)||"(no actions were taken)"]};return{nonContextValues:u,contextMetadata:b,actionLog:ps(L),actorResult:z,actorFieldValues:q}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=wt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let s=this.ai??e,a=n?.debug??this.debug??s?.getOptions()?.debug??!1,{nonContextValues:l,actorResult:u,actorFieldValues:c}=await this._runActorLoop(s,t,n,o),p={...this.options,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};return{...await this.responderProgram.forward(s,{...l,contextData:u},p),...c}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async*streamingForward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=wt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let s=this.ai??e,a=n?.debug??this.debug??s?.getOptions()?.debug??!1,{nonContextValues:l,contextMetadata:u,actorResult:c,actorFieldValues:p}=await this._runActorLoop(s,t,n,o),d={...this.options,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};for await(let m of this.responderProgram.streamingForward(s,{...l,contextMetadata:u,actorResult:c},d))yield m;Object.keys(p).length>0&&(yield{version:1,index:0,delta:p})}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t,n){return async(...r)=>{let o;if(r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0]))o=r[0];else{let s=e.parameters?.properties?Object.keys(e.parameters.properties):[];o={},s.forEach((a,l)=>{l<r.length&&(o[a]=r[l])})}return await e.func(o,{abortSignal:t,ai:n})}}static wrapFunctionWithSharedFields(e,t,n,r){return!n||Object.keys(n).length===0?i.wrapFunction(e,t,r):async(...o)=>{let s;if(o.length===1&&typeof o[0]=="object"&&o[0]!==null&&!Array.isArray(o[0]))s=o[0];else{let l=e.parameters?.properties?Object.keys(e.parameters.properties):[];s={},l.forEach((u,c)=>{c<o.length&&(s[u]=o[c])})}let a={...n,...s};return await e.func(a,{abortSignal:t,ai:r})}}buildRuntimeGlobals(e,t,n){let r={};for(let o of this.collectFunctions())r[o.name]=i.wrapFunction(o,e);if(this.agents&&this.agents.length>0){let o={};for(let s of this.agents){let a=s.getFunction(),l=new Set(s.getExcludedSharedFields?.()??[]),u={};if(t)for(let[c,p]of Object.entries(t))l.has(c)||(u[c]=p);o[a.name]=i.wrapFunctionWithSharedFields(a,e,u,n)}r.agents=o}return r}_buildFuncParameters(){let e=this.program.getSignature().toInputJSONSchema();return this._parentSharedFields.size>0?jp(e,this._parentSharedFields):e}};function wu(i,e){let t=typeof i=="string"?ke.create(i):i,{ai:n,agentIdentity:r,agents:o,functions:s,...a}=e;return new Pr({ai:n,agentIdentity:r,signature:t,agents:o,functions:s},a)}function Dp(i){return i instanceof ze&&i.status>=500&&i.status<600?!0:i instanceof _e||i instanceof Ye}function It(i,e){return i.length<=e?i:`${i.slice(0,e)}
|
|
793
793
|
...[truncated ${i.length-e} chars]`}function Up(i){let e=[];for(let[t,n]of Object.entries(i)){let r=Array.isArray(n)?"array":typeof n,o=typeof n=="string"?`${n.length} chars`:Array.isArray(n)?`${n.length} items`:n&&typeof n=="object"?`${Object.keys(n).length} keys`:"n/a";e.push(`- ${t}: type=${r}, size=${o}`)}return e.join(`
|
|
794
794
|
`)}async function Bp(i,e,t){if(i.length===0)return[];let n=new Array(i.length),r=0,o=Math.max(1,Math.min(e,i.length)),s=Array.from({length:o},async()=>{for(;;){let a=r++;if(a>=i.length)return;let l=i[a];if(l===void 0)return;n[a]=await t(l,a)}});return await Promise.all(s),n}function jp(i,e){if(!i.properties||e.size===0)return i;let t=Object.fromEntries(Object.entries(i.properties).filter(([r])=>!e.has(r))),n=i.required?.filter(r=>!e.has(r));return{...i,properties:t,...n!==void 0?{required:n}:{}}}function qp(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}var Ru=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return es({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,u=await i(l);return{...a,retrievalResult:{retrievedDocument:u,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],u=l.length>0?await Promise.all(l.filter(Boolean).map(c=>i(c))):[];return{...a,retrievalResults:u}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],u=Array.isArray(a.retrievalResults)?a.retrievalResults:[],c=[...l,...u].filter(Boolean);return{collectedEvidence:c.length>0?c:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...Array.isArray(a.allEvidence)?a.allEvidence:[],...Array.isArray(a.retrievalResults)?a.retrievalResults:[]],evidenceSources:[...Array.isArray(a.evidenceSources)?a.evidenceSources:[],`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:(()=>{let l=(a.accumulatedContext||"").toString().trim();if(l.length>0)return l;let u=(a.synthesizedEvidence||"").toString().trim();if(u.length>0)return u;let p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
|
|
795
795
|
`):"").toString().trim();return p.length>0?p:"No context available."})(),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],u=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,c=await i(u);return{...a,healingResult:{healingDocument:c}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};
|