@agentica/chat 0.32.3 → 0.32.4
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/dist/assets/{VendorConfigurationMovie-JTAUbOpa.js → VendorConfigurationMovie-CSiPYSMU.js} +6 -6
- package/dist/assets/bbs/{index-C-fuCqwj.js → index-B0WjRZp-.js} +1 -1
- package/dist/assets/shopping/{index.html-B-SzI_xh.js → index.html-_P-LTLBe.js} +1 -1
- package/dist/assets/uploader/{index.html-D6q2R7cz.js → index.html-BIlPGtIX.js} +1 -1
- package/dist/bbs/index.html +2 -2
- package/dist/shopping/index.html +2 -2
- package/dist/uploader/index.html +2 -2
- package/package.json +2 -2
package/dist/assets/{VendorConfigurationMovie-JTAUbOpa.js → VendorConfigurationMovie-CSiPYSMU.js}
RENAMED
|
@@ -1449,7 +1449,7 @@ You have been provided with \`IValidation.IError[][]\` containing **previous his
|
|
|
1449
1449
|
- Redesign the entire AST structure using proper architectural patterns
|
|
1450
1450
|
- Enhance with comprehensive business context and realistic data
|
|
1451
1451
|
|
|
1452
|
-
**Success means: the error path never appears in future correction cycles.**`};var EDn={};const TDn=new qIe(()=>{var o;return IIe()?((o=EDn.LANG)==null?void 0:o.split(".")[0])??"en-US":navigator.language}),kDn=new qIe(()=>Intl.DateTimeFormat().resolvedOptions().timeZone);function SDn(o){var y;if(((y=o==null?void 0:o.systemPrompt)==null?void 0:y.common)!==void 0)return o.systemPrompt.common(o);const s=(o==null?void 0:o.locale)??TDn.get(),p=(o==null?void 0:o.timezone)??kDn.get();return I6.COMMON.replace("${locale}",s).replace("${timezone}",p).replace("${datetime}",new Date().toISOString())}const s$={write:SDn};function CDn(o){return typeof o.initialize=="function"}function WIe(o){const s=async(p,y,C=0)=>{try{return await p(y)}catch(N){if(C>=o-1)throw N;return s(p,N,C+1)}};return s}class WQ extends Error{constructor(){super()}}class Tmt extends WQ{constructor(s){super(),this.reasoning=s}}var nFt;(o=>{function s(p){return new TextDecoder().decode(p)}o.toUtf8=s})(nFt||(nFt={}));function KIe(o,s){return{accepted_prediction_tokens:(o.accepted_prediction_tokens??0)+(s.accepted_prediction_tokens??0),reasoning_tokens:(o.reasoning_tokens??0)+(s.reasoning_tokens??0),rejected_prediction_tokens:(o.rejected_prediction_tokens??0)+(s.rejected_prediction_tokens??0)}}function GIe(o,s){return{audio_tokens:(o.audio_tokens??0)+(s.audio_tokens??0),cached_tokens:(o.cached_tokens??0)+(s.cached_tokens??0)}}function ADn(o,s){return{prompt_tokens:(o.prompt_tokens??0)+(s.prompt_tokens??0),completion_tokens:(o.completion_tokens??0)+(s.completion_tokens??0),total_tokens:(o.total_tokens??0)+(s.total_tokens??0),completion_tokens_details:KIe(o.completion_tokens_details??{accepted_prediction_tokens:0,reasoning_tokens:0,rejected_prediction_tokens:0},s.completion_tokens_details??{accepted_prediction_tokens:0,reasoning_tokens:0,rejected_prediction_tokens:0}),prompt_tokens_details:GIe(o.prompt_tokens_details??{audio_tokens:0,cached_tokens:0},s.prompt_tokens_details??{audio_tokens:0,cached_tokens:0})}}const IDn={sum:ADn,sumCompletionTokenDetail:KIe,sumPromptTokenDetail:GIe};function ODn(o){const s=o instanceof Uint8Array?nFt.toUtf8(o):o;return JSON.parse(s)}function YIe(o,s){const p=o.choices;s.choices.forEach(C=>{const N=p[C.index];if(N!=null){p[C.index]=VIe(N,C);return}p[C.index]={index:C.index,finish_reason:C.finish_reason??null,logprobs:C.logprobs??null,message:{tool_calls:C.delta.tool_calls!==void 0?C.delta.tool_calls.reduce((L,z)=>{var G,U;return L[z.index]={id:z.id??"",type:"function",function:{name:((G=z.function)==null?void 0:G.name)??"",arguments:((U=z.function)==null?void 0:U.arguments)??""}},L},[]):void 0,content:C.delta.content??null,refusal:C.delta.refusal??null,role:"assistant",reasoning:C.delta.reasoning??null}}});const y=s.usage==null?o.usage:o.usage==null?s.usage:IDn.sum(o.usage,s.usage);return{...o,choices:p,usage:y}}function NDn(o){const s=o[0];if(s===void 0)throw new Error("No chunks received");const p=o.reduce(YIe,{id:s.id,choices:[],created:s.created,model:s.model,object:"chat.completion",usage:void 0,service_tier:s.service_tier,system_fingerprint:s.system_fingerprint});return p.choices.forEach(y=>{var C;(C=y.message.tool_calls)==null||C.forEach(N=>{N.function.arguments===""&&(N.function.arguments="{}")})}),p}function VIe(o,s){var p;if(o.finish_reason==null&&s.finish_reason!=null&&(o.finish_reason=s.finish_reason),o.logprobs==null&&s.logprobs!=null&&(o.logprobs=s.logprobs),s.delta.content!=null&&(o.message.content==null?o.message.content=s.delta.content:o.message.content+=s.delta.content),s.delta.refusal!=null&&(o.message.refusal==null?o.message.refusal=s.delta.refusal:o.message.refusal+=s.delta.refusal),s.delta.reasoning!=null&&(o.message.reasoning==null?o.message.reasoning=s.delta.reasoning:o.message.reasoning+=s.delta.reasoning),s.delta.tool_calls!=null){(p=o.message).tool_calls??(p.tool_calls=[]);const y=o.message.tool_calls;s.delta.tool_calls.forEach(C=>{var L,z;const N=y[C.index];if(N!=null){y[C.index]=XIe(N,C);return}y[C.index]={id:C.id??"",type:"function",function:{name:((L=C.function)==null?void 0:L.name)??"",arguments:((z=C.function)==null?void 0:z.arguments)??""}}})}return o}function XIe(o,s){return s.function!=null&&(o.function.arguments+=s.function.arguments??"",o.function.name+=s.function.name??""),o.id+=s.id??"",o}const dP={transformCompletionChunk:ODn,accumulate:YIe,merge:NDn,mergeChoice:VIe,mergeToolCalls:XIe};class PDn extends Error{constructor(s){super(s),this.name="AsyncQueueClosedError"}}class LDn{constructor(){this.queue=[],this.resolvers=[],this.closeResolvers=[],this.emptyResolvers=[],this.closed=!1}enqueue(s){var p;if(this.closed){console.error(new PDn("Cannot enqueue item: queue is closed."));return}this.queue.push(s),this.resolvers.length>0&&((p=this.resolvers.shift())==null||p({value:this.queue.shift(),done:!1}))}async dequeue(){const s=this.isEmpty()?this.isClosed()?{value:void 0,done:!0}:null:{value:this.queue.shift(),done:!1};return this.isEmpty()&&this.emptyResolvers.length!==0&&(this.emptyResolvers.forEach(p=>p()),this.emptyResolvers=[]),s!==null?s:new Promise(p=>this.resolvers.push(p))}isEmpty(){return this.queue.length===0}isClosed(){return this.closed}done(){return this.isClosed()&&this.isEmpty()}close(){var s;for(this.closed=!0;this.resolvers.length>0;)(s=this.resolvers.shift())==null||s({value:void 0,done:!0});this.closeResolvers.forEach(p=>p())}async waitUntilEmpty(){return this.isEmpty()?Promise.resolve():new Promise(s=>{this.emptyResolvers.push(s)})}async waitClosed(){return this.isClosed()?Promise.resolve():new Promise(s=>{this.closeResolvers.push(s)})}}class MDn{constructor(){this.queue=new LDn,this.consumer=new ReadableStream({start:async s=>{for(;;){const{value:p,done:y}=await this.queue.dequeue();if(y===!0){s.close();return}s.enqueue(p)}}})}produce(s){this.queue.enqueue(s)}close(){this.queue.close()}done(){return this.queue.done()}async waitClosed(){await this.queue.waitClosed()}async waitUntilEmpty(){await this.queue.waitUntilEmpty()}}async function RDn(o){const s=o.getReader(),p=[];for(;;){const{done:y,value:C}=await s.read();if(y)break;p.push(C)}return p}async function DDn(o,s,p){const y=o.getReader(),C=JFt(y);let N=p??null;for await(const L of C){if(N===null){N=L;continue}N=s(N,L)}return N}function BDn(...o){return new ReadableStream({start:p=>{o.forEach(y=>p.enqueue(y)),p.close()}})}async function*QFt(o){yield o}async function*JFt(o){for(;;){const{done:s,value:p}=await o.read();if(s)break;yield p}}function FDn(o,s){const p=o.getReader();return new ReadableStream({pull:async y=>{const{done:C,value:N}=await p.read();C?y.close():y.enqueue(s(N))}})}const KQ={readAll:RDn,reduce:DDn,from:BDn,transform:FDn};async function Jmt(o,s){const p=new Map,y=await KQ.reduce(o,async(C,N)=>{const L=await C,z=G=>{for(const U of G){if(U.delta.content!=null&&U.delta.content!=="")if(p.has(U.index)){const et=p.get(U.index);et.content+=U.delta.content,et.mpsc.produce(U.delta.content)}else{const et=new MDn;p.set(U.index,{content:U.delta.content,mpsc:et}),et.produce(U.delta.content),s({stream:JFt(et.consumer.getReader()),done:()=>et.done(),get:()=>{var tt;return((tt=p.get(U.index))==null?void 0:tt.content)??""},join:async()=>(await et.waitClosed(),p.get(U.index).content)})}if(U.finish_reason!=null){const et=p.get(U.index);et!=null&&et.mpsc.close()}}};return L.object==="chat.completion.chunk"?(z([L,N].flatMap(G=>G.choices)),dP.merge([L,N])):(z(N.choices),dP.accumulate(L,N))});if(y==null)throw new Error(`StreamUtil.reduce did not produce a ChatCompletion. Possible causes: the input stream was empty, invalid, or closed prematurely. To debug: check that the stream is properly initialized and contains valid ChatCompletionChunk data. You may also enable verbose logging upstream to inspect the stream contents. Stream locked: ${o.locked}.`);if(y.object==="chat.completion.chunk"){const C=dP.merge([y]);return C.choices.forEach(N=>{N.message.content!=null&&N.message.content!==""&&s({stream:QFt(N.message.content),done:()=>!0,get:()=>N.message.content,join:async()=>N.message.content})}),C}return y}function Zmt(o){return{operation:o.operation,reason:o.reason,toJSON:()=>({operation:o.operation.toJSON(),reason:o.reason})}}function QIe(o,s){const p=o.stack.findIndex(N=>N.operation.name===s.name);if(p===-1)return;const y=o.stack[p];o.stack.splice(p,1);const C=aRn({selection:Zmt({operation:y.operation,reason:s.reason})});o.dispatch(C)}async function $Dn(o,s){var z,G;const p=WIe(((z=o.config)==null?void 0:z.retry)??a5.RETRY),C=await(async U=>p(U).catch(et=>{if(et instanceof WQ)return Symbol("emptyAssistantMessage");throw et}))(async U=>{var st,at,Ot,Rt,At,ie,ae;const et=await o.request("call",{messages:[{role:"system",content:s$.write(o.config)},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},...U instanceof Tmt?[{role:"assistant",content:U.reasoning}]:[],...((at=(st=o.config)==null?void 0:st.systemPrompt)==null?void 0:at.execute)===null?[]:[{role:"system",content:((At=(Rt=(Ot=o.config)==null?void 0:Ot.systemPrompt)==null?void 0:Rt.execute)==null?void 0:At.call(Rt,o.histories))??I6.EXECUTE}]],tools:s.map(ge=>({type:"function",function:{name:ge.name,description:ge.function.description,parameters:"separated"in ge.function&&ge.function.separated!==void 0?ge.function.separated.llm??{type:"object",properties:{},required:[],additionalProperties:!1,$defs:{}}:ge.function.parameters}})),tool_choice:"auto"}),tt=await Jmt(et,ge=>{const Je=UQ(ge);o.dispatch(Je).catch(()=>{})});if(tt.choices.every(ge=>ge.message.tool_calls==null&&ge.message.content==="")){const ge=tt.choices.at(0);throw((ie=ge==null?void 0:ge.message)==null?void 0:ie.reasoning)!=null?new Tmt(((ae=ge==null?void 0:ge.message)==null?void 0:ae.reasoning)??""):new WQ}return tt});if(typeof C=="symbol"){const U=UQ({stream:QFt(""),done:()=>!0,get:()=>"",join:async()=>""});return o.dispatch(U).catch(()=>{}),[]}const N=[],L=((G=o.config)==null?void 0:G.retry)??a5.RETRY;for(const U of C.choices)for(const et of U.message.tool_calls??[])if(et.type==="function"){const tt=s.find(st=>st.name===et.function.name);if(tt===void 0)continue;const nt=await JIe(o,tt,et,[],L);await o.dispatch(nt),N.push(nt),CDn(o)&&QIe(o,{name:nt.operation.name,reason:"completed"})}return N}async function JIe(o,s,p,y,C){const N=zDn(s,p);if(await o.dispatch(N),N.type==="jsonParseError")return HDn(o,N,y,C-1);const L=s.function.validate(N.arguments);if(L.success===!1){const z=cRn({id:p.id,operation:s,result:L});return await o.dispatch(z),jDn(o,N,z,[...y,z],C-1)}return UDn(N,s)}async function jDn(o,s,p,y,C){var N,L,z;return ZIe(o,{giveUp:()=>ymt({operation:s.operation,arguments:s.arguments,value:{name:"ValidationError",message:`Invalid arguments. The validation failed after ${a5.RETRY} retries.`,errors:p.result.errors},success:!1}),operation:s.operation,toolCall:{id:s.id,arguments:JSON.stringify(s.arguments),result:JSON.stringify(p.result.errors)},systemPrompt:((z=(L=(N=o.config)==null?void 0:N.systemPrompt)==null?void 0:L.validate)==null?void 0:z.call(L,y.slice(0,-1)))??[I6.VALIDATE,...y.length>1?["",I6.VALIDATE_REPEATED.replace("${{HISTORICAL_ERRORS}}",JSON.stringify(y.slice(0,-1).map(G=>G.result.errors)))]:[]].join(`
|
|
1452
|
+
**Success means: the error path never appears in future correction cycles.**`};var EDn={};const TDn=new qIe(()=>{var o;return IIe()?((o=EDn.LANG)==null?void 0:o.split(".")[0])??"en-US":navigator.language}),kDn=new qIe(()=>Intl.DateTimeFormat().resolvedOptions().timeZone);function SDn(o){var y;if(((y=o==null?void 0:o.systemPrompt)==null?void 0:y.common)!==void 0)return o.systemPrompt.common(o);const s=(o==null?void 0:o.locale)??TDn.get(),p=(o==null?void 0:o.timezone)??kDn.get();return I6.COMMON.replace("${locale}",s).replace("${timezone}",p).replace("${datetime}",new Date().toISOString())}const s$={write:SDn};function CDn(o){return typeof o.initialize=="function"}function WIe(o){const s=async(p,y,C=0)=>{try{return await p(y)}catch(N){if(C>=o-1)throw N;return s(p,N,C+1)}};return s}class WQ extends Error{constructor(){super()}}class Tmt extends WQ{constructor(s){super(),this.reasoning=s}}var nFt;(o=>{function s(p){return new TextDecoder().decode(p)}o.toUtf8=s})(nFt||(nFt={}));function KIe(o,s){return{accepted_prediction_tokens:(o.accepted_prediction_tokens??0)+(s.accepted_prediction_tokens??0),reasoning_tokens:(o.reasoning_tokens??0)+(s.reasoning_tokens??0),rejected_prediction_tokens:(o.rejected_prediction_tokens??0)+(s.rejected_prediction_tokens??0)}}function GIe(o,s){return{audio_tokens:(o.audio_tokens??0)+(s.audio_tokens??0),cached_tokens:(o.cached_tokens??0)+(s.cached_tokens??0)}}function ADn(o,s){return{prompt_tokens:(o.prompt_tokens??0)+(s.prompt_tokens??0),completion_tokens:(o.completion_tokens??0)+(s.completion_tokens??0),total_tokens:(o.total_tokens??0)+(s.total_tokens??0),completion_tokens_details:KIe(o.completion_tokens_details??{accepted_prediction_tokens:0,reasoning_tokens:0,rejected_prediction_tokens:0},s.completion_tokens_details??{accepted_prediction_tokens:0,reasoning_tokens:0,rejected_prediction_tokens:0}),prompt_tokens_details:GIe(o.prompt_tokens_details??{audio_tokens:0,cached_tokens:0},s.prompt_tokens_details??{audio_tokens:0,cached_tokens:0})}}const IDn={sum:ADn,sumCompletionTokenDetail:KIe,sumPromptTokenDetail:GIe};function ODn(o){const s=o instanceof Uint8Array?nFt.toUtf8(o):o;return JSON.parse(s)}function YIe(o,s){const p=o.choices;s.choices.forEach(C=>{const N=p[C.index];if(N!=null){p[C.index]=VIe(N,C);return}p[C.index]={index:C.index,finish_reason:C.finish_reason??null,logprobs:C.logprobs??null,message:{tool_calls:C.delta.tool_calls!==void 0?C.delta.tool_calls.reduce((L,z)=>{var G,U;return L[z.index]={id:z.id??"",type:"function",function:{name:((G=z.function)==null?void 0:G.name)??"",arguments:((U=z.function)==null?void 0:U.arguments)??""}},L},[]):void 0,content:C.delta.content??null,refusal:C.delta.refusal??null,role:"assistant",reasoning:C.delta.reasoning??null}}});const y=s.usage==null?o.usage:o.usage==null?s.usage:IDn.sum(o.usage,s.usage);return{...o,choices:p,usage:y}}function NDn(o){const s=o[0];if(s===void 0)throw new Error("No chunks received");const p=o.reduce(YIe,{id:s.id,choices:[],created:s.created,model:s.model,object:"chat.completion",usage:void 0,service_tier:s.service_tier,system_fingerprint:s.system_fingerprint});return p.choices.forEach(y=>{var C;(C=y.message.tool_calls)==null||C.forEach(N=>{N.function.arguments===""&&(N.function.arguments="{}")})}),p}function VIe(o,s){var p;if(o.finish_reason==null&&s.finish_reason!=null&&(o.finish_reason=s.finish_reason),o.logprobs==null&&s.logprobs!=null&&(o.logprobs=s.logprobs),s.delta.content!=null&&(o.message.content==null?o.message.content=s.delta.content:o.message.content+=s.delta.content),s.delta.refusal!=null&&(o.message.refusal==null?o.message.refusal=s.delta.refusal:o.message.refusal+=s.delta.refusal),s.delta.reasoning!=null&&(o.message.reasoning==null?o.message.reasoning=s.delta.reasoning:o.message.reasoning+=s.delta.reasoning),s.delta.tool_calls!=null){(p=o.message).tool_calls??(p.tool_calls=[]);const y=o.message.tool_calls;s.delta.tool_calls.forEach(C=>{var L,z;const N=y[C.index];if(N!=null){y[C.index]=XIe(N,C);return}y[C.index]={id:C.id??"",type:"function",function:{name:((L=C.function)==null?void 0:L.name)??"",arguments:((z=C.function)==null?void 0:z.arguments)??""}}})}return o}function XIe(o,s){return s.function!=null&&(o.function.arguments+=s.function.arguments??"",o.function.name+=s.function.name??""),o.id+=s.id??"",o}const dP={transformCompletionChunk:ODn,accumulate:YIe,merge:NDn,mergeChoice:VIe,mergeToolCalls:XIe};class PDn extends Error{constructor(s){super(s),this.name="AsyncQueueClosedError"}}class LDn{constructor(){this.queue=[],this.resolvers=[],this.closeResolvers=[],this.emptyResolvers=[],this.closed=!1}enqueue(s){var p;if(this.closed){console.error(new PDn("Cannot enqueue item: queue is closed."));return}this.queue.push(s),this.resolvers.length>0&&((p=this.resolvers.shift())==null||p({value:this.queue.shift(),done:!1}))}async dequeue(){const s=this.isEmpty()?this.isClosed()?{value:void 0,done:!0}:null:{value:this.queue.shift(),done:!1};return this.isEmpty()&&this.emptyResolvers.length!==0&&(this.emptyResolvers.forEach(p=>p()),this.emptyResolvers=[]),s!==null?s:new Promise(p=>this.resolvers.push(p))}isEmpty(){return this.queue.length===0}isClosed(){return this.closed}done(){return this.isClosed()&&this.isEmpty()}close(){var s;for(this.closed=!0;this.resolvers.length>0;)(s=this.resolvers.shift())==null||s({value:void 0,done:!0});this.closeResolvers.forEach(p=>p())}async waitUntilEmpty(){return this.isEmpty()?Promise.resolve():new Promise(s=>{this.emptyResolvers.push(s)})}async waitClosed(){return this.isClosed()?Promise.resolve():new Promise(s=>{this.closeResolvers.push(s)})}}class MDn{constructor(){this.queue=new LDn,this.consumer=new ReadableStream({start:async s=>{for(;;){const{value:p,done:y}=await this.queue.dequeue();if(y===!0){s.close();return}s.enqueue(p)}}})}produce(s){this.queue.enqueue(s)}close(){this.queue.close()}done(){return this.queue.done()}async waitClosed(){await this.queue.waitClosed()}async waitUntilEmpty(){await this.queue.waitUntilEmpty()}}async function RDn(o,s){const p=o.getReader(),y=[];for(;;){const{done:C,value:N}=await p.read();if(C||(s==null?void 0:s.aborted)===!0)break;y.push(N)}return y}async function DDn(o,s,p){var L;const y=o.getReader(),C=JFt(y);let N=p.initial??null;for await(const z of C){if(((L=p.abortSignal)==null?void 0:L.aborted)===!0)break;if(N===null){N=z;continue}N=s(N,z)}return N}function BDn(...o){return new ReadableStream({start:p=>{o.forEach(y=>p.enqueue(y)),p.close()}})}async function*QFt(o){yield o}async function*JFt(o,s){for(;;){const{done:p,value:y}=await o.read();if(p||(s==null?void 0:s.aborted)===!0)break;yield y}}function FDn(o,s,p){const y=o.getReader();return new ReadableStream({pull:async C=>{const{done:N,value:L}=await y.read();if(N===!0||(p==null?void 0:p.aborted)===!0){C.close();return}C.enqueue(s(L))}})}const KQ={readAll:RDn,reduce:DDn,from:BDn,transform:FDn};async function Jmt(o,s,p){const y=new Map,C=await KQ.reduce(o,async(N,L)=>{const z=await N,G=U=>{for(const et of U){if(et.delta.content!=null&&et.delta.content!=="")if(y.has(et.index)){const tt=y.get(et.index);tt.content+=et.delta.content,tt.mpsc.produce(et.delta.content)}else{const tt=new MDn;y.set(et.index,{content:et.delta.content,mpsc:tt}),tt.produce(et.delta.content),s({stream:JFt(tt.consumer.getReader()),done:()=>tt.done(),get:()=>{var nt;return((nt=y.get(et.index))==null?void 0:nt.content)??""},join:async()=>(await tt.waitClosed(),y.get(et.index).content)})}if(et.finish_reason!=null){const tt=y.get(et.index);tt!=null&&tt.mpsc.close()}}};return z.object==="chat.completion.chunk"?(G([z,L].flatMap(U=>U.choices)),dP.merge([z,L])):(G(L.choices),dP.accumulate(z,L))},{abortSignal:p});if(C==null)throw new Error(`StreamUtil.reduce did not produce a ChatCompletion. Possible causes: the input stream was empty, invalid, or closed prematurely. To debug: check that the stream is properly initialized and contains valid ChatCompletionChunk data. You may also enable verbose logging upstream to inspect the stream contents. Stream locked: ${o.locked}.`);if(C.object==="chat.completion.chunk"){const N=dP.merge([C]);return N.choices.forEach(L=>{L.message.content!=null&&L.message.content!==""&&s({stream:QFt(L.message.content),done:()=>!0,get:()=>L.message.content,join:async()=>L.message.content})}),N}return C}function Zmt(o){return{operation:o.operation,reason:o.reason,toJSON:()=>({operation:o.operation.toJSON(),reason:o.reason})}}function QIe(o,s){const p=o.stack.findIndex(N=>N.operation.name===s.name);if(p===-1)return;const y=o.stack[p];o.stack.splice(p,1);const C=aRn({selection:Zmt({operation:y.operation,reason:s.reason})});o.dispatch(C)}async function $Dn(o,s){var z,G;const p=WIe(((z=o.config)==null?void 0:z.retry)??a5.RETRY),C=await(async U=>p(U).catch(et=>{if(et instanceof WQ)return Symbol("emptyAssistantMessage");throw et}))(async U=>{var st,at,Ot,Rt,At,ie,ae;const et=await o.request("call",{messages:[{role:"system",content:s$.write(o.config)},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},...U instanceof Tmt?[{role:"assistant",content:U.reasoning}]:[],...((at=(st=o.config)==null?void 0:st.systemPrompt)==null?void 0:at.execute)===null?[]:[{role:"system",content:((At=(Rt=(Ot=o.config)==null?void 0:Ot.systemPrompt)==null?void 0:Rt.execute)==null?void 0:At.call(Rt,o.histories))??I6.EXECUTE}]],tools:s.map(ge=>({type:"function",function:{name:ge.name,description:ge.function.description,parameters:"separated"in ge.function&&ge.function.separated!==void 0?ge.function.separated.llm??{type:"object",properties:{},required:[],additionalProperties:!1,$defs:{}}:ge.function.parameters}})),tool_choice:"auto"}),tt=await Jmt(et,ge=>{const Je=UQ(ge);o.dispatch(Je).catch(()=>{}),o.abortSignal});if(tt.choices.every(ge=>ge.message.tool_calls==null&&ge.message.content==="")){const ge=tt.choices.at(0);throw((ie=ge==null?void 0:ge.message)==null?void 0:ie.reasoning)!=null?new Tmt(((ae=ge==null?void 0:ge.message)==null?void 0:ae.reasoning)??""):new WQ}return tt});if(typeof C=="symbol"){const U=UQ({stream:QFt(""),done:()=>!0,get:()=>"",join:async()=>""});return o.dispatch(U).catch(()=>{}),[]}const N=[],L=((G=o.config)==null?void 0:G.retry)??a5.RETRY;for(const U of C.choices)for(const et of U.message.tool_calls??[])if(et.type==="function"){const tt=s.find(st=>st.name===et.function.name);if(tt===void 0)continue;const nt=await JIe(o,tt,et,[],L);await o.dispatch(nt),N.push(nt),CDn(o)&&QIe(o,{name:nt.operation.name,reason:"completed"})}return N}async function JIe(o,s,p,y,C){const N=zDn(s,p);if(await o.dispatch(N),N.type==="jsonParseError")return HDn(o,N,y,C-1);const L=s.function.validate(N.arguments);if(L.success===!1){const z=cRn({id:p.id,operation:s,result:L});return await o.dispatch(z),jDn(o,N,z,[...y,z],C-1)}return UDn(N,s)}async function jDn(o,s,p,y,C){var N,L,z;return ZIe(o,{giveUp:()=>ymt({operation:s.operation,arguments:s.arguments,value:{name:"ValidationError",message:`Invalid arguments. The validation failed after ${a5.RETRY} retries.`,errors:p.result.errors},success:!1}),operation:s.operation,toolCall:{id:s.id,arguments:JSON.stringify(s.arguments),result:JSON.stringify(p.result.errors)},systemPrompt:((z=(L=(N=o.config)==null?void 0:N.systemPrompt)==null?void 0:L.validate)==null?void 0:z.call(L,y.slice(0,-1)))??[I6.VALIDATE,...y.length>1?["",I6.VALIDATE_REPEATED.replace("${{HISTORICAL_ERRORS}}",JSON.stringify(y.slice(0,-1).map(G=>G.result.errors)))]:[]].join(`
|
|
1453
1453
|
`),life:C,previousValidationErrors:y})}async function HDn(o,s,p,y){var C,N,L;return ZIe(o,{giveUp:()=>ymt({operation:s.operation,arguments:{},value:{name:"JsonParseError",message:`Invalid JSON format. The parsing failed after ${a5.RETRY} retries.`,arguments:s.arguments,errorMessage:s.errorMessage},success:!1}),operation:s.operation,toolCall:{id:s.id,arguments:s.arguments,result:s.errorMessage},systemPrompt:((L=(N=(C=o.config)==null?void 0:C.systemPrompt)==null?void 0:N.jsonParseError)==null?void 0:L.call(N,s))??I6.JSON_PARSE_ERROR.replace("${{ERROR_MESSAGE}}",s.errorMessage),life:y,previousValidationErrors:p})}function zDn(o,s){try{const p=JSON.parse(s.function.arguments);return sRn({id:s.id,operation:o,arguments:p})}catch(p){return oRn({id:s.id,operation:o,arguments:s.function.arguments,errorMessage:p instanceof Error?p.message:String(p)})}}async function ZIe(o,s){var L,z,G,U,et,tt;if(s.life<=0)return s.giveUp();const p=await o.request("call",{messages:[{role:"system",content:s$.write(o.config)},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},{role:"system",content:((G=(z=(L=o.config)==null?void 0:L.systemPrompt)==null?void 0:z.execute)==null?void 0:G.call(z,o.histories))??I6.EXECUTE},{role:"assistant",tool_calls:[{type:"function",id:s.toolCall.id,function:{name:s.operation.name,arguments:s.toolCall.arguments}}]},{role:"tool",content:s.toolCall.result,tool_call_id:s.toolCall.id},{role:"system",content:s.systemPrompt}],tools:[{type:"function",function:{name:s.operation.name,description:s.operation.function.description,parameters:"separated"in s.operation.function&&s.operation.function.separated!==void 0?((U=s.operation.function.separated)==null?void 0:U.llm)??{$defs:{},type:"object",properties:{},additionalProperties:!1,required:[]}:s.operation.function.parameters}}],tool_choice:"required"}),y=await KQ.readAll(p),N=(tt=(et=dP.merge(y).choices[0])==null?void 0:et.message.tool_calls)==null?void 0:tt.find(nt=>nt.function.name===s.operation.name);return N===void 0?s.giveUp():JIe(o,s.operation,N,s.previousValidationErrors,s.life)}async function UDn(o,s){try{const p=await(async()=>{switch(s.protocol){case"class":return qDn(o,s);case"http":return WDn(o,s);case"mcp":return KDn(o,s);default:throw new Error("Unknown protocol")}})();return ymt({operation:o.operation,arguments:o.arguments,value:p,success:!0})}catch(p){return ymt({operation:o.operation,arguments:o.arguments,value:p instanceof Error?{...p,name:p.name,message:p.message}:p,success:!1})}}async function qDn(o,s){const p=s.controller.execute;return typeof p=="function"?await p({application:s.controller.application,function:s.function,arguments:o.arguments}):await p[s.function.name](o.arguments)}async function WDn(o,s){const p=s.controller.execute;return typeof p=="function"?await p({connection:s.controller.connection,application:s.controller.application,function:s.function,arguments:o.arguments}):await eFt.propagate({connection:s.controller.connection,application:s.controller.application,function:s.function,input:o.arguments})}async function KDn(o,s){return s.controller.client.callTool({method:s.function.name,name:s.function.name,arguments:o.arguments}).then(p=>p.content)}var ZFt={};Object.defineProperty(ZFt,"__esModule",{value:!0});var o$=ZFt._validateReport=void 0;const GDn=o=>{const s=p=>{if(o.length===0)return!0;const y=o[o.length-1].path;return p.length>y.length||y.substring(0,p.length)!==p};return(p,y)=>{var C;return p&&s(y.path)&&(y.value===void 0&&((C=y.description)!==null&&C!==void 0||(y.description=["The value at this path is `undefined`.","",`Please fill the \`${y.expected}\` typed value next time.`].join(`
|
|
1454
1454
|
`))),o.push(y)),!1}};o$=ZFt._validateReport=GDn;const KDt={functions:[{name:"cancelFunctions",parameters:{description:` Properties of the function
|
|
1455
1455
|
|
|
@@ -1470,8 +1470,8 @@ agent selects multiple candidate functions because the A.I. agent can't specify
|
|
|
1470
1470
|
only one thing due to lack of specificity or homogeneity of candidate functions.
|
|
1471
1471
|
|
|
1472
1472
|
Additionally, if you A.I. agent wants to cancel same function multiply, you can
|
|
1473
|
-
do it by assigning the same function name multiply in the \`functions\` property.`,validate:(()=>{const o=z=>Array.isArray(z.functions)&&z.functions.every(G=>typeof G=="object"&&G!==null&&s(G)),s=z=>typeof z.reason=="string"&&typeof z.name=="string",p=(z,G,U=!0)=>[(Array.isArray(z.functions)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions}))&&z.functions.map((et,tt)=>(typeof et=="object"&&et!==null||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et}))&&y(et,G+".functions["+tt+"]",U)||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et})).every(et=>et)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions})].every(et=>et),y=(z,G,U=!0)=>[typeof z.reason=="string"||L(U,{path:G+".reason",expected:"string",value:z.reason}),typeof z.name=="string"||L(U,{path:G+".name",expected:"string",value:z.name})].every(et=>et),C=z=>typeof z=="object"&&z!==null&&o(z);let N,L;return z=>{if(C(z)===!1){N=[],L=o$(N),((U,et,tt=!0)=>(typeof U=="object"&&U!==null||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))&&p(U,et+"",!0)||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))(z,"$input",!0);const G=N.length===0;return G?{success:G,data:z}:{success:G,errors:N,data:z}}return{success:!0,data:z}}})()}]};async function YDn(o){var y;if(o.operations.divided===void 0)return zbt(o,o.operations.array,0);const s=o.operations.divided.map(()=>[]),p=[];if(await Promise.all(o.operations.divided.map(async(C,N)=>zbt({...o,stack:s[N],dispatch:async L=>{p.push(L)}},C,0))),(((y=o.config)==null?void 0:y.eliticism)??a5.ELITICISM)===!0&&s.some(C=>C.length!==0))return zbt(o,s.flat().map(C=>o.operations.group.get(C.operation.controller.name).get(C.operation.function.name)),0);{const C=p.filter(N=>N.type==="cancel");(C.length!==0?C:p).forEach(N=>{o.dispatch(N).catch(()=>{})})}}async function zbt(o,s,p,y){var z,G,U,et;const C=await o.request("cancel",{messages:[{role:"system",content:s$.write(o.config)},{role:"assistant",tool_calls:[{type:"function",id:"getApiFunctions",function:{name:"getApiFunctions",arguments:JSON.stringify({})}}]},{role:"tool",tool_call_id:"getApiFunctions",content:JSON.stringify(s.map(tt=>({name:tt.name,description:tt.function.description,...tt.protocol==="http"?{method:tt.function.method,path:tt.function.path,tags:tt.function.tags}:{}})))},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},{role:"system",content:((U=(G=(z=o.config)==null?void 0:z.systemPrompt)==null?void 0:G.cancel)==null?void 0:U.call(G,o.histories))??I6.CANCEL},...VDn(y??[])],tools:[{type:"function",function:{name:KDt.functions[0].name,description:KDt.functions[0].description,parameters:KDt.functions[0].parameters}}],tool_choice:p===0?"auto":"required"}),N=await KQ.readAll(C),L=dP.merge(N);if(p++<(((et=o.config)==null?void 0:et.retry)??a5.RETRY)){const tt=[];for(const nt of L.choices)for(const st of nt.message.tool_calls??[]){if(st.function.name!=="cancelFunctions")continue;const at=JSON.parse(st.function.arguments),Ot=(()=>{const Rt=pn=>Array.isArray(pn.functions)&&pn.functions.every(tr=>typeof tr=="object"&&tr!==null&&At(tr)),At=pn=>typeof pn.reason=="string"&&typeof pn.name=="string",ie=(pn,tr,zn=!0)=>[(Array.isArray(pn.functions)||de(zn,{path:tr+".functions",expected:"Array<___IChatFunctionReference>",value:pn.functions}))&&pn.functions.map((Xn,cr)=>(typeof Xn=="object"&&Xn!==null||de(zn,{path:tr+".functions["+cr+"]",expected:"___IChatFunctionReference",value:Xn}))&&ae(Xn,tr+".functions["+cr+"]",zn)||de(zn,{path:tr+".functions["+cr+"]",expected:"___IChatFunctionReference",value:Xn})).every(Xn=>Xn)||de(zn,{path:tr+".functions",expected:"Array<___IChatFunctionReference>",value:pn.functions})].every(Xn=>Xn),ae=(pn,tr,zn=!0)=>[typeof pn.reason=="string"||de(zn,{path:tr+".reason",expected:"string",value:pn.reason}),typeof pn.name=="string"||de(zn,{path:tr+".name",expected:"string",value:pn.name})].every(Xn=>Xn),ge=pn=>typeof pn=="object"&&pn!==null&&Rt(pn);let Je,de;return pn=>{if(ge(pn)===!1){Je=[],de=o$(Je),((zn,Xn,cr=!0)=>(typeof zn=="object"&&zn!==null||de(!0,{path:Xn+"",expected:"__IChatFunctionReference.IProps",value:zn}))&&ie(zn,Xn+"",!0)||de(!0,{path:Xn+"",expected:"__IChatFunctionReference.IProps",value:zn}))(pn,"$input",!0);const tr=Je.length===0;return tr?{success:tr,data:pn}:{success:tr,errors:Je,data:pn}}return{success:!0,data:pn}}})()(at);Ot.success===!1&&tt.push({id:st.id,name:st.function.name,validation:Ot})}if(tt.length>0)return zbt(o,s,p,tt)}for(const tt of L.choices)if(tt.message.tool_calls!=null)for(const nt of tt.message.tool_calls){if(nt.type!=="function")continue;if(nt.function.name!=="cancelFunctions")continue;const st=(()=>{const at=At=>Array.isArray(At.functions)&&At.functions.every(ie=>typeof ie=="object"&&ie!==null&&Ot(ie)),Ot=At=>typeof At.reason=="string"&&typeof At.name=="string",Rt=At=>typeof At=="object"&&At!==null&&at(At);return At=>(At=JSON.parse(At),Rt(At)?At:null)})()(nt.function.arguments);if(st!==null)for(const at of st.functions)QIe(o,at)}}function VDn(o){return o.map(s=>[{role:"assistant",tool_calls:[{type:"function",id:s.id,function:{name:s.name,arguments:JSON.stringify(s.validation.data)}}]},{role:"tool",content:JSON.stringify(s.validation.errors),tool_call_id:s.id},{role:"system",content:["You A.I. assistant has composed wrong typed arguments.","","Correct it at the next function calling."].join(`
|
|
1474
|
-
`)}]).flat()}async function XDn(o,s){var y,C,N;if(s.length===0)return;const p=await o.request("describe",{messages:[{role:"system",content:s$.write(o.config)},...s.map(i$).flat(),{role:"system",content:((N=(C=(y=o.config)==null?void 0:y.systemPrompt)==null?void 0:C.describe)==null?void 0:N.call(C,s))??I6.DESCRIBE}]});await Jmt(p,L=>{const z=lRn({executes:s,...L});o.dispatch(z)})}const Abt=[{name:"getApiFunctions",parameters:{description:"Current Type: {@link object}",type:"object",properties:{},required:[],additionalProperties:!1,$defs:{IHttpLlmFunctionchatgpt:{description:`LLM function calling schema from HTTP (OpenAPI) operation.
|
|
1473
|
+
do it by assigning the same function name multiply in the \`functions\` property.`,validate:(()=>{const o=z=>Array.isArray(z.functions)&&z.functions.every(G=>typeof G=="object"&&G!==null&&s(G)),s=z=>typeof z.reason=="string"&&typeof z.name=="string",p=(z,G,U=!0)=>[(Array.isArray(z.functions)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions}))&&z.functions.map((et,tt)=>(typeof et=="object"&&et!==null||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et}))&&y(et,G+".functions["+tt+"]",U)||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et})).every(et=>et)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions})].every(et=>et),y=(z,G,U=!0)=>[typeof z.reason=="string"||L(U,{path:G+".reason",expected:"string",value:z.reason}),typeof z.name=="string"||L(U,{path:G+".name",expected:"string",value:z.name})].every(et=>et),C=z=>typeof z=="object"&&z!==null&&o(z);let N,L;return z=>{if(C(z)===!1){N=[],L=o$(N),((U,et,tt=!0)=>(typeof U=="object"&&U!==null||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))&&p(U,et+"",!0)||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))(z,"$input",!0);const G=N.length===0;return G?{success:G,data:z}:{success:G,errors:N,data:z}}return{success:!0,data:z}}})()}]};async function YDn(o){var y;if(o.operations.divided===void 0)return zbt(o,o.operations.array,0);const s=o.operations.divided.map(()=>[]),p=[];if(await Promise.all(o.operations.divided.map(async(C,N)=>zbt({...o,stack:s[N],dispatch:async L=>{p.push(L)}},C,0))),(((y=o.config)==null?void 0:y.eliticism)??a5.ELITICISM)===!0&&s.some(C=>C.length!==0))return zbt(o,s.flat().map(C=>o.operations.group.get(C.operation.controller.name).get(C.operation.function.name)),0);{const C=p.filter(N=>N.type==="cancel");(C.length!==0?C:p).forEach(N=>{o.dispatch(N).catch(()=>{})})}}async function zbt(o,s,p,y){var z,G,U,et;const C=await o.request("cancel",{messages:[{role:"system",content:s$.write(o.config)},{role:"assistant",tool_calls:[{type:"function",id:"getApiFunctions",function:{name:"getApiFunctions",arguments:JSON.stringify({})}}]},{role:"tool",tool_call_id:"getApiFunctions",content:JSON.stringify(s.map(tt=>({name:tt.name,description:tt.function.description,...tt.protocol==="http"?{method:tt.function.method,path:tt.function.path,tags:tt.function.tags}:{}})))},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},{role:"system",content:((U=(G=(z=o.config)==null?void 0:z.systemPrompt)==null?void 0:G.cancel)==null?void 0:U.call(G,o.histories))??I6.CANCEL},...VDn(y??[])],tools:[{type:"function",function:{name:KDt.functions[0].name,description:KDt.functions[0].description,parameters:KDt.functions[0].parameters}}],tool_choice:p===0?"auto":"required"}),N=await KQ.readAll(C,o.abortSignal),L=dP.merge(N);if(p++<(((et=o.config)==null?void 0:et.retry)??a5.RETRY)){const tt=[];for(const nt of L.choices)for(const st of nt.message.tool_calls??[]){if(st.function.name!=="cancelFunctions")continue;const at=JSON.parse(st.function.arguments),Ot=(()=>{const Rt=pn=>Array.isArray(pn.functions)&&pn.functions.every(tr=>typeof tr=="object"&&tr!==null&&At(tr)),At=pn=>typeof pn.reason=="string"&&typeof pn.name=="string",ie=(pn,tr,zn=!0)=>[(Array.isArray(pn.functions)||de(zn,{path:tr+".functions",expected:"Array<___IChatFunctionReference>",value:pn.functions}))&&pn.functions.map((Xn,cr)=>(typeof Xn=="object"&&Xn!==null||de(zn,{path:tr+".functions["+cr+"]",expected:"___IChatFunctionReference",value:Xn}))&&ae(Xn,tr+".functions["+cr+"]",zn)||de(zn,{path:tr+".functions["+cr+"]",expected:"___IChatFunctionReference",value:Xn})).every(Xn=>Xn)||de(zn,{path:tr+".functions",expected:"Array<___IChatFunctionReference>",value:pn.functions})].every(Xn=>Xn),ae=(pn,tr,zn=!0)=>[typeof pn.reason=="string"||de(zn,{path:tr+".reason",expected:"string",value:pn.reason}),typeof pn.name=="string"||de(zn,{path:tr+".name",expected:"string",value:pn.name})].every(Xn=>Xn),ge=pn=>typeof pn=="object"&&pn!==null&&Rt(pn);let Je,de;return pn=>{if(ge(pn)===!1){Je=[],de=o$(Je),((zn,Xn,cr=!0)=>(typeof zn=="object"&&zn!==null||de(!0,{path:Xn+"",expected:"__IChatFunctionReference.IProps",value:zn}))&&ie(zn,Xn+"",!0)||de(!0,{path:Xn+"",expected:"__IChatFunctionReference.IProps",value:zn}))(pn,"$input",!0);const tr=Je.length===0;return tr?{success:tr,data:pn}:{success:tr,errors:Je,data:pn}}return{success:!0,data:pn}}})()(at);Ot.success===!1&&tt.push({id:st.id,name:st.function.name,validation:Ot})}if(tt.length>0)return zbt(o,s,p,tt)}for(const tt of L.choices)if(tt.message.tool_calls!=null)for(const nt of tt.message.tool_calls){if(nt.type!=="function")continue;if(nt.function.name!=="cancelFunctions")continue;const st=(()=>{const at=At=>Array.isArray(At.functions)&&At.functions.every(ie=>typeof ie=="object"&&ie!==null&&Ot(ie)),Ot=At=>typeof At.reason=="string"&&typeof At.name=="string",Rt=At=>typeof At=="object"&&At!==null&&at(At);return At=>(At=JSON.parse(At),Rt(At)?At:null)})()(nt.function.arguments);if(st!==null)for(const at of st.functions)QIe(o,at)}}function VDn(o){return o.map(s=>[{role:"assistant",tool_calls:[{type:"function",id:s.id,function:{name:s.name,arguments:JSON.stringify(s.validation.data)}}]},{role:"tool",content:JSON.stringify(s.validation.errors),tool_call_id:s.id},{role:"system",content:["You A.I. assistant has composed wrong typed arguments.","","Correct it at the next function calling."].join(`
|
|
1474
|
+
`)}]).flat()}async function XDn(o,s){var y,C,N;if(s.length===0)return;const p=await o.request("describe",{messages:[{role:"system",content:s$.write(o.config)},...s.map(i$).flat(),{role:"system",content:((N=(C=(y=o.config)==null?void 0:y.systemPrompt)==null?void 0:C.describe)==null?void 0:N.call(C,s))??I6.DESCRIBE}]});await Jmt(p,L=>{const z=lRn({executes:s,...L});o.dispatch(z)},o.abortSignal)}const Abt=[{name:"getApiFunctions",parameters:{description:"Current Type: {@link object}",type:"object",properties:{},required:[],additionalProperties:!1,$defs:{IHttpLlmFunctionchatgpt:{description:`LLM function calling schema from HTTP (OpenAPI) operation.
|
|
1475
1475
|
|
|
1476
1476
|
\`IHttpLlmFunction\` is a data structure representing a function converted from
|
|
1477
1477
|
the {@link OpenApi.IOperation OpenAPI operation}, used for the LLM (Large
|
|
@@ -1807,7 +1807,7 @@ call this \`getApiFunctions()\` to get the list of candidate API functions
|
|
|
1807
1807
|
provided from this application.
|
|
1808
1808
|
|
|
1809
1809
|
Also, user just wants to list up every remote API functions that can be
|
|
1810
|
-
called from the backend server, utilize this function too.`,validate:(()=>{const o=N=>!0,s=(N,L,z=!0)=>!0,p=N=>typeof N=="object"&&N!==null&&Array.isArray(N)===!1&&o();let y,C;return N=>{if(p(N)===!1){y=[],C=o$(y),((z,G,U=!0)=>(typeof z=="object"&&z!==null&&Array.isArray(z)===!1||C(!0,{path:G+"",expected:"object",value:z}))&&s(z,G+"",!0)||C(!0,{path:G+"",expected:"object",value:z}))(N,"$input",!0);const L=y.length===0;return L?{success:L,data:N}:{success:L,errors:y,data:N}}return{success:!0,data:N}}})()}][0];async function QDn(o){var y,C,N;const s=await o.request("initialize",{messages:[{role:"system",content:s$.write(o.config)},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},{role:"system",content:((N=(C=(y=o.config)==null?void 0:y.systemPrompt)==null?void 0:C.initialize)==null?void 0:N.call(C,o.histories))??I6.INITIALIZE}],tools:[{type:"function",function:{name:Abt.name,description:Abt.description,parameters:Abt.parameters}}],tool_choice:"auto"}),p=await Jmt(s,L=>{const z=UQ(L);o.dispatch(z)});if(p===null)throw new Error("No completion received");p.choices.some(L=>L.message.tool_calls!=null&&L.message.tool_calls.some(z=>z.type==="function"&&z.function.name===Abt.name))&&await o.initialize()}function JDn(o,s){const p=o.operations.flat.get(s.name);if(p===void 0)return;const y=Zmt({operation:p,reason:s.reason});o.stack.push(y);const C=iRn({selection:y});o.dispatch(C)}const GDt={functions:[{name:"selectFunctions",parameters:{description:` Properties of the function
|
|
1810
|
+
called from the backend server, utilize this function too.`,validate:(()=>{const o=N=>!0,s=(N,L,z=!0)=>!0,p=N=>typeof N=="object"&&N!==null&&Array.isArray(N)===!1&&o();let y,C;return N=>{if(p(N)===!1){y=[],C=o$(y),((z,G,U=!0)=>(typeof z=="object"&&z!==null&&Array.isArray(z)===!1||C(!0,{path:G+"",expected:"object",value:z}))&&s(z,G+"",!0)||C(!0,{path:G+"",expected:"object",value:z}))(N,"$input",!0);const L=y.length===0;return L?{success:L,data:N}:{success:L,errors:y,data:N}}return{success:!0,data:N}}})()}][0];async function QDn(o){var y,C,N;const s=await o.request("initialize",{messages:[{role:"system",content:s$.write(o.config)},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},{role:"system",content:((N=(C=(y=o.config)==null?void 0:y.systemPrompt)==null?void 0:C.initialize)==null?void 0:N.call(C,o.histories))??I6.INITIALIZE}],tools:[{type:"function",function:{name:Abt.name,description:Abt.description,parameters:Abt.parameters}}],tool_choice:"auto"}),p=await Jmt(s,L=>{const z=UQ(L);o.dispatch(z)},o.abortSignal);if(p===null)throw new Error("No completion received");p.choices.some(L=>L.message.tool_calls!=null&&L.message.tool_calls.some(z=>z.type==="function"&&z.function.name===Abt.name))&&await o.initialize()}function JDn(o,s){const p=o.operations.flat.get(s.name);if(p===void 0)return;const y=Zmt({operation:p,reason:s.reason});o.stack.push(y);const C=iRn({selection:y});o.dispatch(C)}const GDt={functions:[{name:"selectFunctions",parameters:{description:` Properties of the function
|
|
1811
1811
|
|
|
1812
1812
|
------------------------------
|
|
1813
1813
|
|
|
@@ -1827,8 +1827,8 @@ them all into the \`functions\` property.
|
|
|
1827
1827
|
Also, if you A.I. agent can't specify a specific function to call due to lack
|
|
1828
1828
|
of specificity or homogeneity of candidate functions, just assign all of them
|
|
1829
1829
|
by in the\` functions\` property\` too. Instead, when you A.I. agent can specify
|
|
1830
|
-
a specific function to call, the others would be eliminated.`,validate:(()=>{const o=z=>Array.isArray(z.functions)&&z.functions.every(G=>typeof G=="object"&&G!==null&&s(G)),s=z=>typeof z.reason=="string"&&typeof z.name=="string",p=(z,G,U=!0)=>[(Array.isArray(z.functions)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions}))&&z.functions.map((et,tt)=>(typeof et=="object"&&et!==null||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et}))&&y(et,G+".functions["+tt+"]",U)||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et})).every(et=>et)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions})].every(et=>et),y=(z,G,U=!0)=>[typeof z.reason=="string"||L(U,{path:G+".reason",expected:"string",value:z.reason}),typeof z.name=="string"||L(U,{path:G+".name",expected:"string",value:z.name})].every(et=>et),C=z=>typeof z=="object"&&z!==null&&o(z);let N,L;return z=>{if(C(z)===!1){N=[],L=o$(N),((U,et,tt=!0)=>(typeof U=="object"&&U!==null||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))&&p(U,et+"",!0)||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))(z,"$input",!0);const G=N.length===0;return G?{success:G,data:z}:{success:G,errors:N,data:z}}return{success:!0,data:z}}})()}]};async function ZDn(o){var y;if(o.operations.divided===void 0)return Ubt(o,o.operations.array,0);const s=o.operations.divided.map(()=>[]),p=[];if(await Promise.all(o.operations.divided.map(async(C,N)=>Ubt({...o,stack:s[N],dispatch:async L=>{p.push(L)}},C,0))),(((y=o.config)==null?void 0:y.eliticism)??a5.ELITICISM)===!0&&s.some(C=>C.length!==0))return Ubt(o,s.flat().map(C=>o.operations.group.get(C.operation.controller.name).get(C.operation.function.name)),0);{const C=p.filter(N=>N.type==="select");(C.length!==0?C:p).forEach(N=>{o.dispatch(N).catch(()=>{})})}}async function Ubt(o,s,p,y){var z,G;const C=WIe(((z=o.config)==null?void 0:z.retry)??a5.RETRY),L=await(async U=>C(U).catch(et=>{if(et instanceof WQ)return Symbol("emptyAssistantMessage");throw et}))(async U=>{var st,at,Ot,Rt,At;const et=await o.request("select",{messages:[{role:"system",content:s$.write(o.config)},{role:"assistant",tool_calls:[{type:"function",id:"getApiFunctions",function:{name:"getApiFunctions",arguments:JSON.stringify({})}}]},{role:"tool",tool_call_id:"getApiFunctions",content:JSON.stringify(s.map(ie=>({name:ie.name,description:ie.function.description,...ie.protocol==="http"?{method:ie.function.method,path:ie.function.path,tags:ie.function.tags}:{}})))},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},...U instanceof Tmt?[{role:"assistant",content:U.reasoning}]:[],{role:"system",content:((Ot=(at=(st=o.config)==null?void 0:st.systemPrompt)==null?void 0:at.select)==null?void 0:Ot.call(at,o.histories))??I6.SELECT},...tBn(y??[])],tools:[{type:"function",function:{name:GDt.functions[0].name,description:GDt.functions[0].description,parameters:GDt.functions[0].parameters}}],tool_choice:p===0?"auto":"required"}),tt=await Jmt(et,ie=>{const ae=UQ(ie);o.dispatch(ae).catch(()=>{})});if(tt.choices.every(ie=>ie.message.tool_calls==null&&ie.message.content==="")){const ie=tt.choices.at(0);throw((Rt=ie==null?void 0:ie.message)==null?void 0:Rt.reasoning)!=null?new Tmt(((At=ie==null?void 0:ie.message)==null?void 0:At.reasoning)??""):new WQ}return tt});if(typeof L=="symbol"){const U=UQ({stream:QFt(""),done:()=>!0,get:()=>"",join:async()=>""});o.dispatch(U).catch(()=>{});return}if(p++<(((G=o.config)==null?void 0:G.retry)??a5.RETRY)){const U=[];for(const et of L.choices)for(const tt of et.message.tool_calls??[]){if(tt.function.name!=="selectFunctions")continue;const nt=JSON.parse(tt.function.arguments),st=(()=>{const at=Je=>Array.isArray(Je.functions)&&Je.functions.every(de=>typeof de=="object"&&de!==null&&Ot(de)),Ot=Je=>typeof Je.reason=="string"&&typeof Je.name=="string",Rt=(Je,de,pn=!0)=>[(Array.isArray(Je.functions)||ge(pn,{path:de+".functions",expected:"Array<___IChatFunctionReference>",value:Je.functions}))&&Je.functions.map((tr,zn)=>(typeof tr=="object"&&tr!==null||ge(pn,{path:de+".functions["+zn+"]",expected:"___IChatFunctionReference",value:tr}))&&At(tr,de+".functions["+zn+"]",pn)||ge(pn,{path:de+".functions["+zn+"]",expected:"___IChatFunctionReference",value:tr})).every(tr=>tr)||ge(pn,{path:de+".functions",expected:"Array<___IChatFunctionReference>",value:Je.functions})].every(tr=>tr),At=(Je,de,pn=!0)=>[typeof Je.reason=="string"||ge(pn,{path:de+".reason",expected:"string",value:Je.reason}),typeof Je.name=="string"||ge(pn,{path:de+".name",expected:"string",value:Je.name})].every(tr=>tr),ie=Je=>typeof Je=="object"&&Je!==null&&at(Je);let ae,ge;return Je=>{if(ie(Je)===!1){ae=[],ge=o$(ae),((pn,tr,zn=!0)=>(typeof pn=="object"&&pn!==null||ge(!0,{path:tr+"",expected:"__IChatFunctionReference.IProps",value:pn}))&&Rt(pn,tr+"",!0)||ge(!0,{path:tr+"",expected:"__IChatFunctionReference.IProps",value:pn}))(Je,"$input",!0);const de=ae.length===0;return de?{success:de,data:Je}:{success:de,errors:ae,data:Je}}return{success:!0,data:Je}}})()(nt);st.success===!1&&U.push({id:tt.id,name:tt.function.name,validation:st})}if(U.length>0)return Ubt(o,s,p,U)}for(const U of L.choices)if(U.message.tool_calls!=null)for(const et of U.message.tool_calls){if(et.type!=="function")continue;if(et.function.name!=="selectFunctions")continue;const tt=(()=>{const nt=Ot=>Array.isArray(Ot.functions)&&Ot.functions.every(Rt=>typeof Rt=="object"&&Rt!==null&&st(Rt)),st=Ot=>typeof Ot.reason=="string"&&typeof Ot.name=="string",at=Ot=>typeof Ot=="object"&&Ot!==null&&nt(Ot);return Ot=>(Ot=JSON.parse(Ot),at(Ot)?Ot:null)})()(et.function.arguments);if(tt!==null)for(const nt of tt.functions)JDn(o,nt)}}function tBn(o){return o.map(s=>[{role:"assistant",tool_calls:[{type:"function",id:s.id,function:{name:s.name,arguments:JSON.stringify(s.validation.data)}}]},{role:"tool",content:JSON.stringify(s.validation.errors),tool_call_id:s.id},{role:"system",content:["You A.I. assistant has composed wrong typed arguments.","","Correct it at the next function calling."].join(`
|
|
1831
|
-
`)}]).flat()}function eBn(o){return async s=>{if(s.ready()===!1){if((o==null?void 0:o.initialize)!==!0&&typeof(o==null?void 0:o.initialize)!="function")await s.initialize();else if(await(typeof(o==null?void 0:o.initialize)=="function"?o.initialize:QDn)(s),s.ready()===!1)return}if(s.stack.length!==0&&await((o==null?void 0:o.cancel)??YDn)(s),await((o==null?void 0:o.select)??ZDn)(s),s.stack.length!==0)for(;;){const p=await((o==null?void 0:o.call)??$Dn)(s,s.stack.map(y=>y.operation));if((o==null?void 0:o.describe)!==null&&(o==null?void 0:o.describe)!==!1&&await(typeof(o==null?void 0:o.describe)=="function"?o.describe:XDn)(s,p),p.length===0||s.stack.length===0)break}}}function nBn(o){return o.history.type==="userMessage"?aBn({history:o.history}):o.history.type==="assistantMessage"?rBn({history:o.history}):o.history.type==="systemMessage"?iBn({history:o.history}):o.history.type==="select"?sBn({operations:o.operations,history:o.history}):o.history.type==="cancel"?oBn({operations:o.operations,history:o.history}):o.history.type==="execute"?tOe({operations:o.operations,history:o.history}):cBn({operations:o.operations,history:o.history})}function rBn(o){return ZMn(o.history)}function iBn(o){return tRn(o.history)}function aBn(o){return HIe(o.history)}function sBn(o){return zIe({id:o.history.id,created_at:o.history.created_at,selection:Zmt({operation:t$t({operations:o.operations,input:o.history.selection.operation}),reason:o.history.selection.reason})})}function oBn(o){return nRn({id:o.history.id,created_at:o.history.created_at,selection:Zmt({operation:t$t({operations:o.operations,input:o.history.selection.operation}),reason:o.history.selection.reason})})}function tOe(o){return UIe({id:o.history.id,created_at:o.history.created_at,operation:t$t({operations:o.operations,input:o.history.operation}),arguments:o.history.arguments,value:o.history.value,success:o.history.success})}function cBn(o){return eRn({id:o.history.id,created_at:o.history.created_at,text:o.history.text,executes:o.history.executes.map(s=>tOe({operations:o.operations,history:s}))})}function t$t(o){var p;const s=(p=o.operations.get(o.input.controller))==null?void 0:p.get(o.input.function);if(s===void 0)throw new Error(`No operation found: (controller: ${o.input.controller}, function: ${o.input.function})`);return s}const uBn=o=>async(s,p)=>{var nt;const y=hRn({source:s,body:{...p,model:o.vendor.model,stream:!0,stream_options:{include_usage:!0}},options:{...o.vendor.options,signal:o.abortSignal}});await o.dispatch(y);const C=((nt=o.config)==null?void 0:nt.backoffStrategy)??(st=>{throw st.error}),N=await(async()=>{let st=0;for(;;)try{return await o.vendor.api.chat.completions.create(y.body,y.options)}catch(at){const Ot=C({count:st,error:at});await new Promise(Rt=>setTimeout(Rt,Ot)),st++}})(),[L,z]=KQ.transform(N.toReadableStream(),st=>dP.transformCompletionChunk(st)).tee(),[G,U]=z.tee();(async()=>{const st=G.getReader();for(;;){const at=await st.read();if(at.done)break;at.value.usage!=null&&$Ie.aggregate({kind:s,completionUsage:at.value.usage,usage:o.usage})}})().catch(()=>{});const[et,tt]=L.tee();return o.dispatch({id:yk(),type:"response",source:s,stream:JFt(et.getReader()),body:y.body,options:y.options,join:async()=>{const st=await KQ.readAll(tt);return dP.merge(st)},created_at:new Date().toISOString()}).catch(()=>{}),U};class kmt{constructor(s){var p,y;this.props=s,this.operations_=YMn.compose({controllers:s.controllers,config:s.config}),this.stack_=[],this.listeners_=new Map,this.histories_=(s.histories??[]).map(C=>nBn({operations:this.operations_.group,history:C})),this.executor_=typeof((p=s.config)==null?void 0:p.executor)=="function"?s.config.executor:eBn(((y=s.config)==null?void 0:y.executor)??null),this.semaphore_=s.vendor.semaphore!=null?typeof s.vendor.semaphore=="object"?s.vendor.semaphore:new OBt(s.vendor.semaphore):null,this.token_usage_=this.props.tokenUsage!==void 0?this.props.tokenUsage instanceof fP?this.props.tokenUsage:new fP(this.props.tokenUsage):fP.zero(),this.ready_=!1}clone(){var s;return new kmt({...this.props,histories:(s=this.props.histories)==null?void 0:s.slice()})}async conversate(s,p={}){const y=[],C=async z=>{try{await this.dispatch(z),"toHistory"in z&&("join"in z?y.push(async()=>(await z.join(),z.toHistory())):y.push(async()=>z.toHistory()))}catch{}},N=uRn({contents:Array.isArray(s)?s:typeof s=="string"?[{type:"text",text:s}]:[s]});C(N).catch(()=>{}),await this.executor_(this.getContext({dispatch:C,prompt:N.toHistory(),abortSignal:p.abortSignal,usage:this.token_usage_}));const L=await Promise.all(y.map(async z=>z()));return this.histories_.push(...L),L}getConfig(){return this.props.config}getVendor(){return this.props.vendor}getControllers(){return this.props.controllers}getOperations(){return this.operations_.array}getHistories(){return this.histories_}getTokenUsage(){return this.token_usage_}getContext(s){const p=uBn({vendor:this.props.vendor,config:this.props.config,dispatch:s.dispatch,abortSignal:s.abortSignal,usage:this.token_usage_});return{operations:this.operations_,config:this.props.config,histories:this.histories_,stack:this.stack_,ready:()=>this.ready_,prompt:s.prompt,abortSignal:s.abortSignal,dispatch:s.dispatch,request:this.semaphore_===null?p:async(y,C)=>{await this.semaphore_.acquire();try{return await p(y,C)}finally{this.semaphore_.release().catch(()=>{})}},initialize:async()=>{this.ready_=!0,s.dispatch(rRn()).catch(()=>{})}}}on(s,p){return jIe(this.listeners_,s,()=>new Set).add(p),this}off(s,p){const y=this.listeners_.get(s);return y!==void 0&&(y.delete(p),y.size===0&&this.listeners_.delete(s)),this}async dispatch(s){const p=this.listeners_.get(s.type);p!==void 0&&await Promise.all(Array.from(p).map(async y=>{try{await y(s)}catch{}}))}}function tc(o,s,p,y,C){if(typeof s=="function"?o!==s||!0:!s.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s.set(o,p),p}function wr(o,s,p,y){if(p==="a"&&!y)throw new TypeError("Private accessor was defined without a getter");if(typeof s=="function"?o!==s||!y:!s.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return p==="m"?y:p==="a"?y.call(o):y?y.value:s.get(o)}let eOe=function(){const{crypto:o}=globalThis;if(o!=null&&o.randomUUID)return eOe=o.randomUUID.bind(o),o.randomUUID();const s=new Uint8Array(1),p=o?()=>o.getRandomValues(s)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,y=>(+y^p()&15>>+y/4).toString(16))};function rFt(o){return typeof o=="object"&&o!==null&&("name"in o&&o.name==="AbortError"||"message"in o&&String(o.message).includes("FetchRequestCanceledException"))}const iFt=o=>{if(o instanceof Error)return o;if(typeof o=="object"&&o!==null){try{if(Object.prototype.toString.call(o)==="[object Error]"){const s=new Error(o.message,o.cause?{cause:o.cause}:{});return o.stack&&(s.stack=o.stack),o.cause&&!s.cause&&(s.cause=o.cause),o.name&&(s.name=o.name),s}}catch{}try{return new Error(JSON.stringify(o))}catch{}}return new Error(o)};class Ho extends Error{}class Lg extends Ho{constructor(s,p,y,C){super(`${Lg.makeMessage(s,p,y)}`),this.status=s,this.headers=C,this.requestID=C==null?void 0:C.get("x-request-id"),this.error=p;const N=p;this.code=N==null?void 0:N.code,this.param=N==null?void 0:N.param,this.type=N==null?void 0:N.type}static makeMessage(s,p,y){const C=p!=null&&p.message?typeof p.message=="string"?p.message:JSON.stringify(p.message):p?JSON.stringify(p):y;return s&&C?`${s} ${C}`:s?`${s} status code (no body)`:C||"(no status code or body)"}static generate(s,p,y,C){if(!s||!C)return new t2t({message:y,cause:iFt(p)});const N=p==null?void 0:p.error;return s===400?new nOe(s,N,y,C):s===401?new rOe(s,N,y,C):s===403?new iOe(s,N,y,C):s===404?new aOe(s,N,y,C):s===409?new sOe(s,N,y,C):s===422?new oOe(s,N,y,C):s===429?new cOe(s,N,y,C):s>=500?new uOe(s,N,y,C):new Lg(s,N,y,C)}}class O3 extends Lg{constructor({message:s}={}){super(void 0,void 0,s||"Request was aborted.",void 0)}}class t2t extends Lg{constructor({message:s,cause:p}){super(void 0,void 0,s||"Connection error.",void 0),p&&(this.cause=p)}}class e$t extends t2t{constructor({message:s}={}){super({message:s??"Request timed out."})}}class nOe extends Lg{}class rOe extends Lg{}class iOe extends Lg{}class aOe extends Lg{}class sOe extends Lg{}class oOe extends Lg{}class cOe extends Lg{}class uOe extends Lg{}class lOe extends Ho{constructor(){super("Could not parse response content as the length limit was reached")}}class hOe extends Ho{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const lBn=/^[a-z][a-z0-9+.-]*:/i,hBn=o=>lBn.test(o);function fBn(o){return typeof o!="object"?{}:o??{}}function dBn(o){if(!o)return!0;for(const s in o)return!1;return!0}function pBn(o,s){return Object.prototype.hasOwnProperty.call(o,s)}function YDt(o){return o!=null&&typeof o=="object"&&!Array.isArray(o)}const gBn=(o,s)=>{if(typeof s!="number"||!Number.isInteger(s))throw new Ho(`${o} must be an integer`);if(s<0)throw new Ho(`${o} must be a positive integer`);return s},bBn=o=>{try{return JSON.parse(o)}catch{return}},eJ=o=>new Promise(s=>setTimeout(s,o)),Smt={off:0,error:200,warn:300,info:400,debug:500},WCe=(o,s,p)=>{if(o){if(pBn(Smt,o))return o;Tb(p).warn(`${s} was set to ${JSON.stringify(o)}, expected one of ${JSON.stringify(Object.keys(Smt))}`)}};function mQ(){}function Ibt(o,s,p){return!s||Smt[o]>Smt[p]?mQ:s[o].bind(s)}const mBn={error:mQ,warn:mQ,info:mQ,debug:mQ};let KCe=new WeakMap;function Tb(o){const s=o.logger,p=o.logLevel??"off";if(!s)return mBn;const y=KCe.get(s);if(y&&y[0]===p)return y[1];const C={error:Ibt("error",s,p),warn:Ibt("warn",s,p),info:Ibt("info",s,p),debug:Ibt("debug",s,p)};return KCe.set(s,[p,C]),C}const aP=o=>(o.options&&(o.options={...o.options},delete o.options.headers),o.headers&&(o.headers=Object.fromEntries((o.headers instanceof Headers?[...o.headers]:Object.entries(o.headers)).map(([s,p])=>[s,s.toLowerCase()==="authorization"||s.toLowerCase()==="cookie"||s.toLowerCase()==="set-cookie"?"***":p]))),"retryOfRequestLogID"in o&&(o.retryOfRequestLogID&&(o.retryOf=o.retryOfRequestLogID),delete o.retryOfRequestLogID),o),DF="5.2.0",yBn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function wBn(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const vBn=()=>{var p;const o=wBn();if(o==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":YCe(Deno.build.os),"X-Stainless-Arch":GCe(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((p=Deno.version)==null?void 0:p.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(o==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":YCe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":GCe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const s=_Bn();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _Bn(){if(typeof navigator>"u"||!navigator)return null;const o=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:s,pattern:p}of o){const y=p.exec(navigator.userAgent);if(y){const C=y[1]||0,N=y[2]||0,L=y[3]||0;return{browser:s,version:`${C}.${N}.${L}`}}}return null}const GCe=o=>o==="x32"?"x32":o==="x86_64"||o==="x64"?"x64":o==="arm"?"arm":o==="aarch64"||o==="arm64"?"arm64":o?`other:${o}`:"unknown",YCe=o=>(o=o.toLowerCase(),o.includes("ios")?"iOS":o==="android"?"Android":o==="darwin"?"MacOS":o==="win32"?"Windows":o==="freebsd"?"FreeBSD":o==="openbsd"?"OpenBSD":o==="linux"?"Linux":o?`Other:${o}`:"Unknown");let VCe;const xBn=()=>VCe??(VCe=vBn());function EBn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function fOe(...o){const s=globalThis.ReadableStream;if(typeof s>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new s(...o)}function dOe(o){let s=Symbol.asyncIterator in o?o[Symbol.asyncIterator]():o[Symbol.iterator]();return fOe({start(){},async pull(p){const{done:y,value:C}=await s.next();y?p.close():p.enqueue(C)},async cancel(){var p;await((p=s.return)==null?void 0:p.call(s))}})}function pOe(o){if(o[Symbol.asyncIterator])return o;const s=o.getReader();return{async next(){try{const p=await s.read();return p!=null&&p.done&&s.releaseLock(),p}catch(p){throw s.releaseLock(),p}},async return(){const p=s.cancel();return s.releaseLock(),await p,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function TBn(o){var y,C;if(o===null||typeof o!="object")return;if(o[Symbol.asyncIterator]){await((C=(y=o[Symbol.asyncIterator]()).return)==null?void 0:C.call(y));return}const s=o.getReader(),p=s.cancel();s.releaseLock(),await p}const kBn=({headers:o,body:s})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(s)}),aFt="RFC3986",sFt={RFC1738:o=>String(o).replace(/%20/g,"+"),RFC3986:o=>String(o)},SBn="RFC1738",CBn=Array.isArray,w6=(()=>{const o=[];for(let s=0;s<256;++s)o.push("%"+((s<16?"0":"")+s.toString(16)).toUpperCase());return o})(),VDt=1024,ABn=(o,s,p,y,C)=>{if(o.length===0)return o;let N=o;if(typeof o=="symbol"?N=Symbol.prototype.toString.call(o):typeof o!="string"&&(N=String(o)),p==="iso-8859-1")return escape(N).replace(/%u[0-9a-f]{4}/gi,function(z){return"%26%23"+parseInt(z.slice(2),16)+"%3B"});let L="";for(let z=0;z<N.length;z+=VDt){const G=N.length>=VDt?N.slice(z,z+VDt):N,U=[];for(let et=0;et<G.length;++et){let tt=G.charCodeAt(et);if(tt===45||tt===46||tt===95||tt===126||tt>=48&&tt<=57||tt>=65&&tt<=90||tt>=97&&tt<=122||C===SBn&&(tt===40||tt===41)){U[U.length]=G.charAt(et);continue}if(tt<128){U[U.length]=w6[tt];continue}if(tt<2048){U[U.length]=w6[192|tt>>6]+w6[128|tt&63];continue}if(tt<55296||tt>=57344){U[U.length]=w6[224|tt>>12]+w6[128|tt>>6&63]+w6[128|tt&63];continue}et+=1,tt=65536+((tt&1023)<<10|G.charCodeAt(et)&1023),U[U.length]=w6[240|tt>>18]+w6[128|tt>>12&63]+w6[128|tt>>6&63]+w6[128|tt&63]}L+=U.join("")}return L};function IBn(o){return!o||typeof o!="object"?!1:!!(o.constructor&&o.constructor.isBuffer&&o.constructor.isBuffer(o))}function XCe(o,s){if(CBn(o)){const p=[];for(let y=0;y<o.length;y+=1)p.push(s(o[y]));return p}return s(o)}const OBn=Object.prototype.hasOwnProperty,gOe={brackets(o){return String(o)+"[]"},comma:"comma",indices(o,s){return String(o)+"["+s+"]"},repeat(o){return String(o)}},x6=Array.isArray,NBn=Array.prototype.push,bOe=function(o,s){NBn.apply(o,x6(s)?s:[s])},PBn=Date.prototype.toISOString,np={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ABn,encodeValuesOnly:!1,format:aFt,formatter:sFt[aFt],indices:!1,serializeDate(o){return PBn.call(o)},skipNulls:!1,strictNullHandling:!1};function LBn(o){return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||typeof o=="symbol"||typeof o=="bigint"}const XDt={};function mOe(o,s,p,y,C,N,L,z,G,U,et,tt,nt,st,at,Ot,Rt,At){let ie=o,ae=At,ge=0,Je=!1;for(;(ae=ae.get(XDt))!==void 0&&!Je;){const Xn=ae.get(o);if(ge+=1,typeof Xn<"u"){if(Xn===ge)throw new RangeError("Cyclic object value");Je=!0}typeof ae.get(XDt)>"u"&&(ge=0)}if(typeof U=="function"?ie=U(s,ie):ie instanceof Date?ie=nt==null?void 0:nt(ie):p==="comma"&&x6(ie)&&(ie=XCe(ie,function(Xn){return Xn instanceof Date?nt==null?void 0:nt(Xn):Xn})),ie===null){if(N)return G&&!Ot?G(s,np.encoder,Rt,"key",st):s;ie=""}if(LBn(ie)||IBn(ie)){if(G){const Xn=Ot?s:G(s,np.encoder,Rt,"key",st);return[(at==null?void 0:at(Xn))+"="+(at==null?void 0:at(G(ie,np.encoder,Rt,"value",st)))]}return[(at==null?void 0:at(s))+"="+(at==null?void 0:at(String(ie)))]}const de=[];if(typeof ie>"u")return de;let pn;if(p==="comma"&&x6(ie))Ot&&G&&(ie=XCe(ie,G)),pn=[{value:ie.length>0?ie.join(",")||null:void 0}];else if(x6(U))pn=U;else{const Xn=Object.keys(ie);pn=et?Xn.sort(et):Xn}const tr=z?String(s).replace(/\./g,"%2E"):String(s),zn=y&&x6(ie)&&ie.length===1?tr+"[]":tr;if(C&&x6(ie)&&ie.length===0)return zn+"[]";for(let Xn=0;Xn<pn.length;++Xn){const cr=pn[Xn],fr=typeof cr=="object"&&typeof cr.value<"u"?cr.value:ie[cr];if(L&&fr===null)continue;const fi=tt&&z?cr.replace(/\./g,"%2E"):cr,pi=x6(ie)?typeof p=="function"?p(zn,fi):zn:zn+(tt?"."+fi:"["+fi+"]");At.set(o,ge);const Or=new WeakMap;Or.set(XDt,At),bOe(de,mOe(fr,pi,p,y,C,N,L,z,p==="comma"&&Ot&&x6(ie)?null:G,U,et,tt,nt,st,at,Ot,Rt,Or))}return de}function MBn(o=np){if(typeof o.allowEmptyArrays<"u"&&typeof o.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof o.encodeDotInKeys<"u"&&typeof o.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(o.encoder!==null&&typeof o.encoder<"u"&&typeof o.encoder!="function")throw new TypeError("Encoder has to be a function.");const s=o.charset||np.charset;if(typeof o.charset<"u"&&o.charset!=="utf-8"&&o.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let p=aFt;if(typeof o.format<"u"){if(!OBn.call(sFt,o.format))throw new TypeError("Unknown format option provided.");p=o.format}const y=sFt[p];let C=np.filter;(typeof o.filter=="function"||x6(o.filter))&&(C=o.filter);let N;if(o.arrayFormat&&o.arrayFormat in gOe?N=o.arrayFormat:"indices"in o?N=o.indices?"indices":"repeat":N=np.arrayFormat,"commaRoundTrip"in o&&typeof o.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const L=typeof o.allowDots>"u"?o.encodeDotInKeys?!0:np.allowDots:!!o.allowDots;return{addQueryPrefix:typeof o.addQueryPrefix=="boolean"?o.addQueryPrefix:np.addQueryPrefix,allowDots:L,allowEmptyArrays:typeof o.allowEmptyArrays=="boolean"?!!o.allowEmptyArrays:np.allowEmptyArrays,arrayFormat:N,charset:s,charsetSentinel:typeof o.charsetSentinel=="boolean"?o.charsetSentinel:np.charsetSentinel,commaRoundTrip:!!o.commaRoundTrip,delimiter:typeof o.delimiter>"u"?np.delimiter:o.delimiter,encode:typeof o.encode=="boolean"?o.encode:np.encode,encodeDotInKeys:typeof o.encodeDotInKeys=="boolean"?o.encodeDotInKeys:np.encodeDotInKeys,encoder:typeof o.encoder=="function"?o.encoder:np.encoder,encodeValuesOnly:typeof o.encodeValuesOnly=="boolean"?o.encodeValuesOnly:np.encodeValuesOnly,filter:C,format:p,formatter:y,serializeDate:typeof o.serializeDate=="function"?o.serializeDate:np.serializeDate,skipNulls:typeof o.skipNulls=="boolean"?o.skipNulls:np.skipNulls,sort:typeof o.sort=="function"?o.sort:null,strictNullHandling:typeof o.strictNullHandling=="boolean"?o.strictNullHandling:np.strictNullHandling}}function RBn(o,s={}){let p=o;const y=MBn(s);let C,N;typeof y.filter=="function"?(N=y.filter,p=N("",p)):x6(y.filter)&&(N=y.filter,C=N);const L=[];if(typeof p!="object"||p===null)return"";const z=gOe[y.arrayFormat],G=z==="comma"&&y.commaRoundTrip;C||(C=Object.keys(p)),y.sort&&C.sort(y.sort);const U=new WeakMap;for(let nt=0;nt<C.length;++nt){const st=C[nt];y.skipNulls&&p[st]===null||bOe(L,mOe(p[st],st,z,G,y.allowEmptyArrays,y.strictNullHandling,y.skipNulls,y.encodeDotInKeys,y.encode?y.encoder:null,y.filter,y.sort,y.allowDots,y.serializeDate,y.format,y.formatter,y.encodeValuesOnly,y.charset,U))}const et=L.join(y.delimiter);let tt=y.addQueryPrefix===!0?"?":"";return y.charsetSentinel&&(y.charset==="iso-8859-1"?tt+="utf8=%26%2310003%3B&":tt+="utf8=%E2%9C%93&"),et.length>0?tt+et:""}function DBn(o){let s=0;for(const C of o)s+=C.length;const p=new Uint8Array(s);let y=0;for(const C of o)p.set(C,y),y+=C.length;return p}let QCe;function n$t(o){let s;return(QCe??(s=new globalThis.TextEncoder,QCe=s.encode.bind(s)))(o)}let JCe;function ZCe(o){let s;return(JCe??(s=new globalThis.TextDecoder,JCe=s.decode.bind(s)))(o)}var _w,xw;class e2t{constructor(){_w.set(this,void 0),xw.set(this,void 0),tc(this,_w,new Uint8Array),tc(this,xw,null)}decode(s){if(s==null)return[];const p=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?n$t(s):s;tc(this,_w,DBn([wr(this,_w,"f"),p]));const y=[];let C;for(;(C=BBn(wr(this,_w,"f"),wr(this,xw,"f")))!=null;){if(C.carriage&&wr(this,xw,"f")==null){tc(this,xw,C.index);continue}if(wr(this,xw,"f")!=null&&(C.index!==wr(this,xw,"f")+1||C.carriage)){y.push(ZCe(wr(this,_w,"f").subarray(0,wr(this,xw,"f")-1))),tc(this,_w,wr(this,_w,"f").subarray(wr(this,xw,"f"))),tc(this,xw,null);continue}const N=wr(this,xw,"f")!==null?C.preceding-1:C.preceding,L=ZCe(wr(this,_w,"f").subarray(0,N));y.push(L),tc(this,_w,wr(this,_w,"f").subarray(C.index)),tc(this,xw,null)}return y}flush(){return wr(this,_w,"f").length?this.decode(`
|
|
1830
|
+
a specific function to call, the others would be eliminated.`,validate:(()=>{const o=z=>Array.isArray(z.functions)&&z.functions.every(G=>typeof G=="object"&&G!==null&&s(G)),s=z=>typeof z.reason=="string"&&typeof z.name=="string",p=(z,G,U=!0)=>[(Array.isArray(z.functions)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions}))&&z.functions.map((et,tt)=>(typeof et=="object"&&et!==null||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et}))&&y(et,G+".functions["+tt+"]",U)||L(U,{path:G+".functions["+tt+"]",expected:"___IChatFunctionReference",value:et})).every(et=>et)||L(U,{path:G+".functions",expected:"Array<___IChatFunctionReference>",value:z.functions})].every(et=>et),y=(z,G,U=!0)=>[typeof z.reason=="string"||L(U,{path:G+".reason",expected:"string",value:z.reason}),typeof z.name=="string"||L(U,{path:G+".name",expected:"string",value:z.name})].every(et=>et),C=z=>typeof z=="object"&&z!==null&&o(z);let N,L;return z=>{if(C(z)===!1){N=[],L=o$(N),((U,et,tt=!0)=>(typeof U=="object"&&U!==null||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))&&p(U,et+"",!0)||L(!0,{path:et+"",expected:"__IChatFunctionReference.IProps",value:U}))(z,"$input",!0);const G=N.length===0;return G?{success:G,data:z}:{success:G,errors:N,data:z}}return{success:!0,data:z}}})()}]};async function ZDn(o){var y;if(o.operations.divided===void 0)return Ubt(o,o.operations.array,0);const s=o.operations.divided.map(()=>[]),p=[];if(await Promise.all(o.operations.divided.map(async(C,N)=>Ubt({...o,stack:s[N],dispatch:async L=>{p.push(L)}},C,0))),(((y=o.config)==null?void 0:y.eliticism)??a5.ELITICISM)===!0&&s.some(C=>C.length!==0))return Ubt(o,s.flat().map(C=>o.operations.group.get(C.operation.controller.name).get(C.operation.function.name)),0);{const C=p.filter(N=>N.type==="select");(C.length!==0?C:p).forEach(N=>{o.dispatch(N).catch(()=>{})})}}async function Ubt(o,s,p,y){var z,G;const C=WIe(((z=o.config)==null?void 0:z.retry)??a5.RETRY),L=await(async U=>C(U).catch(et=>{if(et instanceof WQ)return Symbol("emptyAssistantMessage");throw et}))(async U=>{var st,at,Ot,Rt,At;const et=await o.request("select",{messages:[{role:"system",content:s$.write(o.config)},{role:"assistant",tool_calls:[{type:"function",id:"getApiFunctions",function:{name:"getApiFunctions",arguments:JSON.stringify({})}}]},{role:"tool",tool_call_id:"getApiFunctions",content:JSON.stringify(s.map(ie=>({name:ie.name,description:ie.function.description,...ie.protocol==="http"?{method:ie.function.method,path:ie.function.path,tags:ie.function.tags}:{}})))},...o.histories.map(i$).flat(),{role:"user",content:o.prompt.contents.map(a$)},...U instanceof Tmt?[{role:"assistant",content:U.reasoning}]:[],{role:"system",content:((Ot=(at=(st=o.config)==null?void 0:st.systemPrompt)==null?void 0:at.select)==null?void 0:Ot.call(at,o.histories))??I6.SELECT},...tBn(y??[])],tools:[{type:"function",function:{name:GDt.functions[0].name,description:GDt.functions[0].description,parameters:GDt.functions[0].parameters}}],tool_choice:p===0?"auto":"required"}),tt=await Jmt(et,ie=>{const ae=UQ(ie);o.dispatch(ae).catch(()=>{})},o.abortSignal);if(tt.choices.every(ie=>ie.message.tool_calls==null&&ie.message.content==="")){const ie=tt.choices.at(0);throw((Rt=ie==null?void 0:ie.message)==null?void 0:Rt.reasoning)!=null?new Tmt(((At=ie==null?void 0:ie.message)==null?void 0:At.reasoning)??""):new WQ}return tt});if(typeof L=="symbol"){const U=UQ({stream:QFt(""),done:()=>!0,get:()=>"",join:async()=>""});o.dispatch(U).catch(()=>{});return}if(p++<(((G=o.config)==null?void 0:G.retry)??a5.RETRY)){const U=[];for(const et of L.choices)for(const tt of et.message.tool_calls??[]){if(tt.function.name!=="selectFunctions")continue;const nt=JSON.parse(tt.function.arguments),st=(()=>{const at=Je=>Array.isArray(Je.functions)&&Je.functions.every(de=>typeof de=="object"&&de!==null&&Ot(de)),Ot=Je=>typeof Je.reason=="string"&&typeof Je.name=="string",Rt=(Je,de,pn=!0)=>[(Array.isArray(Je.functions)||ge(pn,{path:de+".functions",expected:"Array<___IChatFunctionReference>",value:Je.functions}))&&Je.functions.map((tr,zn)=>(typeof tr=="object"&&tr!==null||ge(pn,{path:de+".functions["+zn+"]",expected:"___IChatFunctionReference",value:tr}))&&At(tr,de+".functions["+zn+"]",pn)||ge(pn,{path:de+".functions["+zn+"]",expected:"___IChatFunctionReference",value:tr})).every(tr=>tr)||ge(pn,{path:de+".functions",expected:"Array<___IChatFunctionReference>",value:Je.functions})].every(tr=>tr),At=(Je,de,pn=!0)=>[typeof Je.reason=="string"||ge(pn,{path:de+".reason",expected:"string",value:Je.reason}),typeof Je.name=="string"||ge(pn,{path:de+".name",expected:"string",value:Je.name})].every(tr=>tr),ie=Je=>typeof Je=="object"&&Je!==null&&at(Je);let ae,ge;return Je=>{if(ie(Je)===!1){ae=[],ge=o$(ae),((pn,tr,zn=!0)=>(typeof pn=="object"&&pn!==null||ge(!0,{path:tr+"",expected:"__IChatFunctionReference.IProps",value:pn}))&&Rt(pn,tr+"",!0)||ge(!0,{path:tr+"",expected:"__IChatFunctionReference.IProps",value:pn}))(Je,"$input",!0);const de=ae.length===0;return de?{success:de,data:Je}:{success:de,errors:ae,data:Je}}return{success:!0,data:Je}}})()(nt);st.success===!1&&U.push({id:tt.id,name:tt.function.name,validation:st})}if(U.length>0)return Ubt(o,s,p,U)}for(const U of L.choices)if(U.message.tool_calls!=null)for(const et of U.message.tool_calls){if(et.type!=="function")continue;if(et.function.name!=="selectFunctions")continue;const tt=(()=>{const nt=Ot=>Array.isArray(Ot.functions)&&Ot.functions.every(Rt=>typeof Rt=="object"&&Rt!==null&&st(Rt)),st=Ot=>typeof Ot.reason=="string"&&typeof Ot.name=="string",at=Ot=>typeof Ot=="object"&&Ot!==null&&nt(Ot);return Ot=>(Ot=JSON.parse(Ot),at(Ot)?Ot:null)})()(et.function.arguments);if(tt!==null)for(const nt of tt.functions)JDn(o,nt)}}function tBn(o){return o.map(s=>[{role:"assistant",tool_calls:[{type:"function",id:s.id,function:{name:s.name,arguments:JSON.stringify(s.validation.data)}}]},{role:"tool",content:JSON.stringify(s.validation.errors),tool_call_id:s.id},{role:"system",content:["You A.I. assistant has composed wrong typed arguments.","","Correct it at the next function calling."].join(`
|
|
1831
|
+
`)}]).flat()}function eBn(o){return async s=>{if(s.ready()===!1){if((o==null?void 0:o.initialize)!==!0&&typeof(o==null?void 0:o.initialize)!="function")await s.initialize();else if(await(typeof(o==null?void 0:o.initialize)=="function"?o.initialize:QDn)(s),s.ready()===!1)return}if(s.stack.length!==0&&await((o==null?void 0:o.cancel)??YDn)(s),await((o==null?void 0:o.select)??ZDn)(s),s.stack.length!==0)for(;;){const p=await((o==null?void 0:o.call)??$Dn)(s,s.stack.map(y=>y.operation));if((o==null?void 0:o.describe)!==null&&(o==null?void 0:o.describe)!==!1&&await(typeof(o==null?void 0:o.describe)=="function"?o.describe:XDn)(s,p),p.length===0||s.stack.length===0)break}}}function nBn(o){return o.history.type==="userMessage"?aBn({history:o.history}):o.history.type==="assistantMessage"?rBn({history:o.history}):o.history.type==="systemMessage"?iBn({history:o.history}):o.history.type==="select"?sBn({operations:o.operations,history:o.history}):o.history.type==="cancel"?oBn({operations:o.operations,history:o.history}):o.history.type==="execute"?tOe({operations:o.operations,history:o.history}):cBn({operations:o.operations,history:o.history})}function rBn(o){return ZMn(o.history)}function iBn(o){return tRn(o.history)}function aBn(o){return HIe(o.history)}function sBn(o){return zIe({id:o.history.id,created_at:o.history.created_at,selection:Zmt({operation:t$t({operations:o.operations,input:o.history.selection.operation}),reason:o.history.selection.reason})})}function oBn(o){return nRn({id:o.history.id,created_at:o.history.created_at,selection:Zmt({operation:t$t({operations:o.operations,input:o.history.selection.operation}),reason:o.history.selection.reason})})}function tOe(o){return UIe({id:o.history.id,created_at:o.history.created_at,operation:t$t({operations:o.operations,input:o.history.operation}),arguments:o.history.arguments,value:o.history.value,success:o.history.success})}function cBn(o){return eRn({id:o.history.id,created_at:o.history.created_at,text:o.history.text,executes:o.history.executes.map(s=>tOe({operations:o.operations,history:s}))})}function t$t(o){var p;const s=(p=o.operations.get(o.input.controller))==null?void 0:p.get(o.input.function);if(s===void 0)throw new Error(`No operation found: (controller: ${o.input.controller}, function: ${o.input.function})`);return s}const uBn=o=>async(s,p)=>{var nt;const y=hRn({source:s,body:{...p,model:o.vendor.model,stream:!0,stream_options:{include_usage:!0}},options:{...o.vendor.options,signal:o.abortSignal}});await o.dispatch(y);const C=((nt=o.config)==null?void 0:nt.backoffStrategy)??(st=>{throw st.error}),N=await(async()=>{let st=0;for(;;)try{return await o.vendor.api.chat.completions.create(y.body,y.options)}catch(at){const Ot=C({count:st,error:at});await new Promise(Rt=>setTimeout(Rt,Ot)),st++}})(),[L,z]=KQ.transform(N.toReadableStream(),st=>dP.transformCompletionChunk(st),o.abortSignal).tee(),[G,U]=z.tee();(async()=>{var at;const st=G.getReader();for(;;){const Ot=await st.read();if(Ot.done||((at=o.abortSignal)==null?void 0:at.aborted)===!0)break;Ot.value.usage!=null&&$Ie.aggregate({kind:s,completionUsage:Ot.value.usage,usage:o.usage})}})().catch(()=>{});const[et,tt]=L.tee();return o.dispatch({id:yk(),type:"response",source:s,stream:JFt(et.getReader(),o.abortSignal),body:y.body,options:y.options,join:async()=>{const st=await KQ.readAll(tt,o.abortSignal);return dP.merge(st)},created_at:new Date().toISOString()}).catch(()=>{}),U};class kmt{constructor(s){var p,y;this.props=s,this.operations_=YMn.compose({controllers:s.controllers,config:s.config}),this.stack_=[],this.listeners_=new Map,this.histories_=(s.histories??[]).map(C=>nBn({operations:this.operations_.group,history:C})),this.executor_=typeof((p=s.config)==null?void 0:p.executor)=="function"?s.config.executor:eBn(((y=s.config)==null?void 0:y.executor)??null),this.semaphore_=s.vendor.semaphore!=null?typeof s.vendor.semaphore=="object"?s.vendor.semaphore:new OBt(s.vendor.semaphore):null,this.token_usage_=this.props.tokenUsage!==void 0?this.props.tokenUsage instanceof fP?this.props.tokenUsage:new fP(this.props.tokenUsage):fP.zero(),this.ready_=!1}clone(){var s;return new kmt({...this.props,histories:(s=this.props.histories)==null?void 0:s.slice()})}async conversate(s,p={}){const y=[],C=async z=>{try{await this.dispatch(z),"toHistory"in z&&("join"in z?y.push(async()=>(await z.join(),z.toHistory())):y.push(async()=>z.toHistory()))}catch{}},N=uRn({contents:Array.isArray(s)?s:typeof s=="string"?[{type:"text",text:s}]:[s]});C(N).catch(()=>{}),await this.executor_(this.getContext({dispatch:C,prompt:N.toHistory(),abortSignal:p.abortSignal,usage:this.token_usage_}));const L=await Promise.all(y.map(async z=>z()));return this.histories_.push(...L),L}getConfig(){return this.props.config}getVendor(){return this.props.vendor}getControllers(){return this.props.controllers}getOperations(){return this.operations_.array}getHistories(){return this.histories_}getTokenUsage(){return this.token_usage_}getContext(s){const p=uBn({vendor:this.props.vendor,config:this.props.config,dispatch:s.dispatch,abortSignal:s.abortSignal,usage:this.token_usage_});return{operations:this.operations_,config:this.props.config,histories:this.histories_,stack:this.stack_,ready:()=>this.ready_,prompt:s.prompt,abortSignal:s.abortSignal,dispatch:s.dispatch,request:this.semaphore_===null?p:async(y,C)=>{await this.semaphore_.acquire();try{return await p(y,C)}finally{this.semaphore_.release().catch(()=>{})}},initialize:async()=>{this.ready_=!0,s.dispatch(rRn()).catch(()=>{})}}}on(s,p){return jIe(this.listeners_,s,()=>new Set).add(p),this}off(s,p){const y=this.listeners_.get(s);return y!==void 0&&(y.delete(p),y.size===0&&this.listeners_.delete(s)),this}async dispatch(s){const p=this.listeners_.get(s.type);p!==void 0&&await Promise.all(Array.from(p).map(async y=>{try{await y(s)}catch{}}))}}function tc(o,s,p,y,C){if(typeof s=="function"?o!==s||!0:!s.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s.set(o,p),p}function wr(o,s,p,y){if(p==="a"&&!y)throw new TypeError("Private accessor was defined without a getter");if(typeof s=="function"?o!==s||!y:!s.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return p==="m"?y:p==="a"?y.call(o):y?y.value:s.get(o)}let eOe=function(){const{crypto:o}=globalThis;if(o!=null&&o.randomUUID)return eOe=o.randomUUID.bind(o),o.randomUUID();const s=new Uint8Array(1),p=o?()=>o.getRandomValues(s)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,y=>(+y^p()&15>>+y/4).toString(16))};function rFt(o){return typeof o=="object"&&o!==null&&("name"in o&&o.name==="AbortError"||"message"in o&&String(o.message).includes("FetchRequestCanceledException"))}const iFt=o=>{if(o instanceof Error)return o;if(typeof o=="object"&&o!==null){try{if(Object.prototype.toString.call(o)==="[object Error]"){const s=new Error(o.message,o.cause?{cause:o.cause}:{});return o.stack&&(s.stack=o.stack),o.cause&&!s.cause&&(s.cause=o.cause),o.name&&(s.name=o.name),s}}catch{}try{return new Error(JSON.stringify(o))}catch{}}return new Error(o)};class Ho extends Error{}class Lg extends Ho{constructor(s,p,y,C){super(`${Lg.makeMessage(s,p,y)}`),this.status=s,this.headers=C,this.requestID=C==null?void 0:C.get("x-request-id"),this.error=p;const N=p;this.code=N==null?void 0:N.code,this.param=N==null?void 0:N.param,this.type=N==null?void 0:N.type}static makeMessage(s,p,y){const C=p!=null&&p.message?typeof p.message=="string"?p.message:JSON.stringify(p.message):p?JSON.stringify(p):y;return s&&C?`${s} ${C}`:s?`${s} status code (no body)`:C||"(no status code or body)"}static generate(s,p,y,C){if(!s||!C)return new t2t({message:y,cause:iFt(p)});const N=p==null?void 0:p.error;return s===400?new nOe(s,N,y,C):s===401?new rOe(s,N,y,C):s===403?new iOe(s,N,y,C):s===404?new aOe(s,N,y,C):s===409?new sOe(s,N,y,C):s===422?new oOe(s,N,y,C):s===429?new cOe(s,N,y,C):s>=500?new uOe(s,N,y,C):new Lg(s,N,y,C)}}class O3 extends Lg{constructor({message:s}={}){super(void 0,void 0,s||"Request was aborted.",void 0)}}class t2t extends Lg{constructor({message:s,cause:p}){super(void 0,void 0,s||"Connection error.",void 0),p&&(this.cause=p)}}class e$t extends t2t{constructor({message:s}={}){super({message:s??"Request timed out."})}}class nOe extends Lg{}class rOe extends Lg{}class iOe extends Lg{}class aOe extends Lg{}class sOe extends Lg{}class oOe extends Lg{}class cOe extends Lg{}class uOe extends Lg{}class lOe extends Ho{constructor(){super("Could not parse response content as the length limit was reached")}}class hOe extends Ho{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const lBn=/^[a-z][a-z0-9+.-]*:/i,hBn=o=>lBn.test(o);function fBn(o){return typeof o!="object"?{}:o??{}}function dBn(o){if(!o)return!0;for(const s in o)return!1;return!0}function pBn(o,s){return Object.prototype.hasOwnProperty.call(o,s)}function YDt(o){return o!=null&&typeof o=="object"&&!Array.isArray(o)}const gBn=(o,s)=>{if(typeof s!="number"||!Number.isInteger(s))throw new Ho(`${o} must be an integer`);if(s<0)throw new Ho(`${o} must be a positive integer`);return s},bBn=o=>{try{return JSON.parse(o)}catch{return}},eJ=o=>new Promise(s=>setTimeout(s,o)),Smt={off:0,error:200,warn:300,info:400,debug:500},WCe=(o,s,p)=>{if(o){if(pBn(Smt,o))return o;Tb(p).warn(`${s} was set to ${JSON.stringify(o)}, expected one of ${JSON.stringify(Object.keys(Smt))}`)}};function mQ(){}function Ibt(o,s,p){return!s||Smt[o]>Smt[p]?mQ:s[o].bind(s)}const mBn={error:mQ,warn:mQ,info:mQ,debug:mQ};let KCe=new WeakMap;function Tb(o){const s=o.logger,p=o.logLevel??"off";if(!s)return mBn;const y=KCe.get(s);if(y&&y[0]===p)return y[1];const C={error:Ibt("error",s,p),warn:Ibt("warn",s,p),info:Ibt("info",s,p),debug:Ibt("debug",s,p)};return KCe.set(s,[p,C]),C}const aP=o=>(o.options&&(o.options={...o.options},delete o.options.headers),o.headers&&(o.headers=Object.fromEntries((o.headers instanceof Headers?[...o.headers]:Object.entries(o.headers)).map(([s,p])=>[s,s.toLowerCase()==="authorization"||s.toLowerCase()==="cookie"||s.toLowerCase()==="set-cookie"?"***":p]))),"retryOfRequestLogID"in o&&(o.retryOfRequestLogID&&(o.retryOf=o.retryOfRequestLogID),delete o.retryOfRequestLogID),o),DF="5.2.0",yBn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function wBn(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const vBn=()=>{var p;const o=wBn();if(o==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":YCe(Deno.build.os),"X-Stainless-Arch":GCe(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((p=Deno.version)==null?void 0:p.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(o==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":YCe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":GCe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const s=_Bn();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":DF,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _Bn(){if(typeof navigator>"u"||!navigator)return null;const o=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:s,pattern:p}of o){const y=p.exec(navigator.userAgent);if(y){const C=y[1]||0,N=y[2]||0,L=y[3]||0;return{browser:s,version:`${C}.${N}.${L}`}}}return null}const GCe=o=>o==="x32"?"x32":o==="x86_64"||o==="x64"?"x64":o==="arm"?"arm":o==="aarch64"||o==="arm64"?"arm64":o?`other:${o}`:"unknown",YCe=o=>(o=o.toLowerCase(),o.includes("ios")?"iOS":o==="android"?"Android":o==="darwin"?"MacOS":o==="win32"?"Windows":o==="freebsd"?"FreeBSD":o==="openbsd"?"OpenBSD":o==="linux"?"Linux":o?`Other:${o}`:"Unknown");let VCe;const xBn=()=>VCe??(VCe=vBn());function EBn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function fOe(...o){const s=globalThis.ReadableStream;if(typeof s>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new s(...o)}function dOe(o){let s=Symbol.asyncIterator in o?o[Symbol.asyncIterator]():o[Symbol.iterator]();return fOe({start(){},async pull(p){const{done:y,value:C}=await s.next();y?p.close():p.enqueue(C)},async cancel(){var p;await((p=s.return)==null?void 0:p.call(s))}})}function pOe(o){if(o[Symbol.asyncIterator])return o;const s=o.getReader();return{async next(){try{const p=await s.read();return p!=null&&p.done&&s.releaseLock(),p}catch(p){throw s.releaseLock(),p}},async return(){const p=s.cancel();return s.releaseLock(),await p,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function TBn(o){var y,C;if(o===null||typeof o!="object")return;if(o[Symbol.asyncIterator]){await((C=(y=o[Symbol.asyncIterator]()).return)==null?void 0:C.call(y));return}const s=o.getReader(),p=s.cancel();s.releaseLock(),await p}const kBn=({headers:o,body:s})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(s)}),aFt="RFC3986",sFt={RFC1738:o=>String(o).replace(/%20/g,"+"),RFC3986:o=>String(o)},SBn="RFC1738",CBn=Array.isArray,w6=(()=>{const o=[];for(let s=0;s<256;++s)o.push("%"+((s<16?"0":"")+s.toString(16)).toUpperCase());return o})(),VDt=1024,ABn=(o,s,p,y,C)=>{if(o.length===0)return o;let N=o;if(typeof o=="symbol"?N=Symbol.prototype.toString.call(o):typeof o!="string"&&(N=String(o)),p==="iso-8859-1")return escape(N).replace(/%u[0-9a-f]{4}/gi,function(z){return"%26%23"+parseInt(z.slice(2),16)+"%3B"});let L="";for(let z=0;z<N.length;z+=VDt){const G=N.length>=VDt?N.slice(z,z+VDt):N,U=[];for(let et=0;et<G.length;++et){let tt=G.charCodeAt(et);if(tt===45||tt===46||tt===95||tt===126||tt>=48&&tt<=57||tt>=65&&tt<=90||tt>=97&&tt<=122||C===SBn&&(tt===40||tt===41)){U[U.length]=G.charAt(et);continue}if(tt<128){U[U.length]=w6[tt];continue}if(tt<2048){U[U.length]=w6[192|tt>>6]+w6[128|tt&63];continue}if(tt<55296||tt>=57344){U[U.length]=w6[224|tt>>12]+w6[128|tt>>6&63]+w6[128|tt&63];continue}et+=1,tt=65536+((tt&1023)<<10|G.charCodeAt(et)&1023),U[U.length]=w6[240|tt>>18]+w6[128|tt>>12&63]+w6[128|tt>>6&63]+w6[128|tt&63]}L+=U.join("")}return L};function IBn(o){return!o||typeof o!="object"?!1:!!(o.constructor&&o.constructor.isBuffer&&o.constructor.isBuffer(o))}function XCe(o,s){if(CBn(o)){const p=[];for(let y=0;y<o.length;y+=1)p.push(s(o[y]));return p}return s(o)}const OBn=Object.prototype.hasOwnProperty,gOe={brackets(o){return String(o)+"[]"},comma:"comma",indices(o,s){return String(o)+"["+s+"]"},repeat(o){return String(o)}},x6=Array.isArray,NBn=Array.prototype.push,bOe=function(o,s){NBn.apply(o,x6(s)?s:[s])},PBn=Date.prototype.toISOString,np={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ABn,encodeValuesOnly:!1,format:aFt,formatter:sFt[aFt],indices:!1,serializeDate(o){return PBn.call(o)},skipNulls:!1,strictNullHandling:!1};function LBn(o){return typeof o=="string"||typeof o=="number"||typeof o=="boolean"||typeof o=="symbol"||typeof o=="bigint"}const XDt={};function mOe(o,s,p,y,C,N,L,z,G,U,et,tt,nt,st,at,Ot,Rt,At){let ie=o,ae=At,ge=0,Je=!1;for(;(ae=ae.get(XDt))!==void 0&&!Je;){const Xn=ae.get(o);if(ge+=1,typeof Xn<"u"){if(Xn===ge)throw new RangeError("Cyclic object value");Je=!0}typeof ae.get(XDt)>"u"&&(ge=0)}if(typeof U=="function"?ie=U(s,ie):ie instanceof Date?ie=nt==null?void 0:nt(ie):p==="comma"&&x6(ie)&&(ie=XCe(ie,function(Xn){return Xn instanceof Date?nt==null?void 0:nt(Xn):Xn})),ie===null){if(N)return G&&!Ot?G(s,np.encoder,Rt,"key",st):s;ie=""}if(LBn(ie)||IBn(ie)){if(G){const Xn=Ot?s:G(s,np.encoder,Rt,"key",st);return[(at==null?void 0:at(Xn))+"="+(at==null?void 0:at(G(ie,np.encoder,Rt,"value",st)))]}return[(at==null?void 0:at(s))+"="+(at==null?void 0:at(String(ie)))]}const de=[];if(typeof ie>"u")return de;let pn;if(p==="comma"&&x6(ie))Ot&&G&&(ie=XCe(ie,G)),pn=[{value:ie.length>0?ie.join(",")||null:void 0}];else if(x6(U))pn=U;else{const Xn=Object.keys(ie);pn=et?Xn.sort(et):Xn}const tr=z?String(s).replace(/\./g,"%2E"):String(s),zn=y&&x6(ie)&&ie.length===1?tr+"[]":tr;if(C&&x6(ie)&&ie.length===0)return zn+"[]";for(let Xn=0;Xn<pn.length;++Xn){const cr=pn[Xn],fr=typeof cr=="object"&&typeof cr.value<"u"?cr.value:ie[cr];if(L&&fr===null)continue;const fi=tt&&z?cr.replace(/\./g,"%2E"):cr,pi=x6(ie)?typeof p=="function"?p(zn,fi):zn:zn+(tt?"."+fi:"["+fi+"]");At.set(o,ge);const Or=new WeakMap;Or.set(XDt,At),bOe(de,mOe(fr,pi,p,y,C,N,L,z,p==="comma"&&Ot&&x6(ie)?null:G,U,et,tt,nt,st,at,Ot,Rt,Or))}return de}function MBn(o=np){if(typeof o.allowEmptyArrays<"u"&&typeof o.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof o.encodeDotInKeys<"u"&&typeof o.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(o.encoder!==null&&typeof o.encoder<"u"&&typeof o.encoder!="function")throw new TypeError("Encoder has to be a function.");const s=o.charset||np.charset;if(typeof o.charset<"u"&&o.charset!=="utf-8"&&o.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let p=aFt;if(typeof o.format<"u"){if(!OBn.call(sFt,o.format))throw new TypeError("Unknown format option provided.");p=o.format}const y=sFt[p];let C=np.filter;(typeof o.filter=="function"||x6(o.filter))&&(C=o.filter);let N;if(o.arrayFormat&&o.arrayFormat in gOe?N=o.arrayFormat:"indices"in o?N=o.indices?"indices":"repeat":N=np.arrayFormat,"commaRoundTrip"in o&&typeof o.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const L=typeof o.allowDots>"u"?o.encodeDotInKeys?!0:np.allowDots:!!o.allowDots;return{addQueryPrefix:typeof o.addQueryPrefix=="boolean"?o.addQueryPrefix:np.addQueryPrefix,allowDots:L,allowEmptyArrays:typeof o.allowEmptyArrays=="boolean"?!!o.allowEmptyArrays:np.allowEmptyArrays,arrayFormat:N,charset:s,charsetSentinel:typeof o.charsetSentinel=="boolean"?o.charsetSentinel:np.charsetSentinel,commaRoundTrip:!!o.commaRoundTrip,delimiter:typeof o.delimiter>"u"?np.delimiter:o.delimiter,encode:typeof o.encode=="boolean"?o.encode:np.encode,encodeDotInKeys:typeof o.encodeDotInKeys=="boolean"?o.encodeDotInKeys:np.encodeDotInKeys,encoder:typeof o.encoder=="function"?o.encoder:np.encoder,encodeValuesOnly:typeof o.encodeValuesOnly=="boolean"?o.encodeValuesOnly:np.encodeValuesOnly,filter:C,format:p,formatter:y,serializeDate:typeof o.serializeDate=="function"?o.serializeDate:np.serializeDate,skipNulls:typeof o.skipNulls=="boolean"?o.skipNulls:np.skipNulls,sort:typeof o.sort=="function"?o.sort:null,strictNullHandling:typeof o.strictNullHandling=="boolean"?o.strictNullHandling:np.strictNullHandling}}function RBn(o,s={}){let p=o;const y=MBn(s);let C,N;typeof y.filter=="function"?(N=y.filter,p=N("",p)):x6(y.filter)&&(N=y.filter,C=N);const L=[];if(typeof p!="object"||p===null)return"";const z=gOe[y.arrayFormat],G=z==="comma"&&y.commaRoundTrip;C||(C=Object.keys(p)),y.sort&&C.sort(y.sort);const U=new WeakMap;for(let nt=0;nt<C.length;++nt){const st=C[nt];y.skipNulls&&p[st]===null||bOe(L,mOe(p[st],st,z,G,y.allowEmptyArrays,y.strictNullHandling,y.skipNulls,y.encodeDotInKeys,y.encode?y.encoder:null,y.filter,y.sort,y.allowDots,y.serializeDate,y.format,y.formatter,y.encodeValuesOnly,y.charset,U))}const et=L.join(y.delimiter);let tt=y.addQueryPrefix===!0?"?":"";return y.charsetSentinel&&(y.charset==="iso-8859-1"?tt+="utf8=%26%2310003%3B&":tt+="utf8=%E2%9C%93&"),et.length>0?tt+et:""}function DBn(o){let s=0;for(const C of o)s+=C.length;const p=new Uint8Array(s);let y=0;for(const C of o)p.set(C,y),y+=C.length;return p}let QCe;function n$t(o){let s;return(QCe??(s=new globalThis.TextEncoder,QCe=s.encode.bind(s)))(o)}let JCe;function ZCe(o){let s;return(JCe??(s=new globalThis.TextDecoder,JCe=s.decode.bind(s)))(o)}var _w,xw;class e2t{constructor(){_w.set(this,void 0),xw.set(this,void 0),tc(this,_w,new Uint8Array),tc(this,xw,null)}decode(s){if(s==null)return[];const p=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?n$t(s):s;tc(this,_w,DBn([wr(this,_w,"f"),p]));const y=[];let C;for(;(C=BBn(wr(this,_w,"f"),wr(this,xw,"f")))!=null;){if(C.carriage&&wr(this,xw,"f")==null){tc(this,xw,C.index);continue}if(wr(this,xw,"f")!=null&&(C.index!==wr(this,xw,"f")+1||C.carriage)){y.push(ZCe(wr(this,_w,"f").subarray(0,wr(this,xw,"f")-1))),tc(this,_w,wr(this,_w,"f").subarray(wr(this,xw,"f"))),tc(this,xw,null);continue}const N=wr(this,xw,"f")!==null?C.preceding-1:C.preceding,L=ZCe(wr(this,_w,"f").subarray(0,N));y.push(L),tc(this,_w,wr(this,_w,"f").subarray(C.index)),tc(this,xw,null)}return y}flush(){return wr(this,_w,"f").length?this.decode(`
|
|
1832
1832
|
`):[]}}_w=new WeakMap,xw=new WeakMap;e2t.NEWLINE_CHARS=new Set([`
|
|
1833
1833
|
`,"\r"]);e2t.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function BBn(o,s){for(let C=s??0;C<o.length;C++){if(o[C]===10)return{preceding:C,index:C+1,carriage:!1};if(o[C]===13)return{preceding:C,index:C+1,carriage:!0}}return null}function FBn(o){for(let y=0;y<o.length-1;y++){if(o[y]===10&&o[y+1]===10||o[y]===13&&o[y+1]===13)return y+2;if(o[y]===13&&o[y+1]===10&&y+3<o.length&&o[y+2]===13&&o[y+3]===10)return y+4}return-1}class C6{constructor(s,p){this.iterator=s,this.controller=p}static fromSSEResponse(s,p){let y=!1;async function*C(){if(y)throw new Ho("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");y=!0;let N=!1;try{for await(const L of $Bn(s,p))if(!N){if(L.data.startsWith("[DONE]")){N=!0;continue}if(L.event===null||L.event.startsWith("response.")||L.event.startsWith("transcript.")){let z;try{z=JSON.parse(L.data)}catch(G){throw console.error("Could not parse message into JSON:",L.data),console.error("From chunk:",L.raw),G}if(z&&z.error)throw new Lg(void 0,z.error,void 0,s.headers);yield z}else{let z;try{z=JSON.parse(L.data)}catch(G){throw console.error("Could not parse message into JSON:",L.data),console.error("From chunk:",L.raw),G}if(L.event=="error")throw new Lg(void 0,z.error,z.message,void 0);yield{event:L.event,data:z}}}N=!0}catch(L){if(rFt(L))return;throw L}finally{N||p.abort()}}return new C6(C,p)}static fromReadableStream(s,p){let y=!1;async function*C(){const L=new e2t,z=pOe(s);for await(const G of z)for(const U of L.decode(G))yield U;for(const G of L.flush())yield G}async function*N(){if(y)throw new Ho("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");y=!0;let L=!1;try{for await(const z of C())L||z&&(yield JSON.parse(z));L=!0}catch(z){if(rFt(z))return;throw z}finally{L||p.abort()}}return new C6(N,p)}[Symbol.asyncIterator](){return this.iterator()}tee(){const s=[],p=[],y=this.iterator(),C=N=>({next:()=>{if(N.length===0){const L=y.next();s.push(L),p.push(L)}return N.shift()}});return[new C6(()=>C(s),this.controller),new C6(()=>C(p),this.controller)]}toReadableStream(){const s=this;let p;return fOe({async start(){p=s[Symbol.asyncIterator]()},async pull(y){try{const{value:C,done:N}=await p.next();if(N)return y.close();const L=n$t(JSON.stringify(C)+`
|
|
1834
1834
|
`);y.enqueue(L)}catch(C){y.error(C)}},async cancel(){var y;await((y=p.return)==null?void 0:y.call(p))}})}}async function*$Bn(o,s){if(!o.body)throw s.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ho("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ho("Attempted to iterate over a response with no body");const p=new HBn,y=new e2t,C=pOe(o.body);for await(const N of jBn(C))for(const L of y.decode(N)){const z=p.decode(L);z&&(yield z)}for(const N of y.flush()){const L=p.decode(N);L&&(yield L)}}async function*jBn(o){let s=new Uint8Array;for await(const p of o){if(p==null)continue;const y=p instanceof ArrayBuffer?new Uint8Array(p):typeof p=="string"?n$t(p):p;let C=new Uint8Array(s.length+y.length);C.set(s),C.set(y,s.length),s=C;let N;for(;(N=FBn(s))!==-1;)yield s.slice(0,N),s=s.slice(N)}s.length>0&&(yield s)}class HBn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(s){if(s.endsWith("\r")&&(s=s.substring(0,s.length-1)),!s){if(!this.event&&!this.data.length)return null;const N={event:this.event,data:this.data.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as m,o as C,r as b,T as g}from"../client-B3aq8qpT.js";import{q as w,t as T,r as v,s as j,w as x,x as _,y as P,z as R,E as U,v as $,d as k,_ as y,V as A,c as F,F as M,T as q,B as S}from"../VendorConfigurationMovie-
|
|
1
|
+
import{j as m,o as C,r as b,T as g}from"../client-B3aq8qpT.js";import{q as w,t as T,r as v,s as j,w as x,x as _,y as P,z as R,E as U,v as $,d as k,_ as y,V as A,c as F,F as M,T as q,B as S}from"../VendorConfigurationMovie-CSiPYSMU.js";import{a as u,_ as p}from"../_isFormatUri-YqTfGpHo.js";import{D}from"../Divider-DX1xhf0M.js";class I{constructor(o){this.props=o,this.operations_=w.compose({controllers:o.controllers,config:o.config}),this.histories_=(o.histories??[]).map(d=>T({operations:this.operations_.group,history:d})),this.token_usage_=this.props.tokenUsage!==void 0?this.props.tokenUsage instanceof v?this.props.tokenUsage:new v(this.props.tokenUsage):v.zero(),this.listeners_=new Map,this.semaphore_=o.vendor.semaphore!=null?typeof o.vendor.semaphore=="object"?o.vendor.semaphore:new j(o.vendor.semaphore):null}clone(){var o;return new I({...this.props,histories:(o=this.props.histories)==null?void 0:o.slice()})}async conversate(o,d={}){var i,n,h,B;const s=[],l=async f=>{try{await this.dispatch(f),"toHistory"in f&&("join"in f?s.push(async()=>(await f.join(),f.toHistory())):s.push(async()=>f.toHistory()))}catch{}},a=x({contents:Array.isArray(o)?o:typeof o=="string"?[{type:"text",text:o}]:[o]});l(a).catch(()=>{});const r=this.getContext({prompt:a,dispatch:l,usage:this.token_usage_,abortSignal:d.abortSignal}),e=await _(r,this.operations_.array);e.length&&((n=(i=this.props.config)==null?void 0:i.executor)==null?void 0:n.describe)!==null&&((B=(h=this.props.config)==null?void 0:h.executor)==null?void 0:B.describe)!==!1&&await P(r,e);const t=await Promise.all(s.map(async f=>f()));return this.histories_.push(...t),t}getConfig(){return this.props.config}getVendor(){return this.props.vendor}getOperations(){return this.operations_.array}getControllers(){return this.props.controllers}getHistories(){return this.histories_}getTokenUsage(){return this.token_usage_}getContext(o){const d=R({vendor:this.props.vendor,config:this.props.config,dispatch:o.dispatch,abortSignal:o.abortSignal,usage:this.token_usage_});return{operations:this.operations_,config:this.props.config,histories:this.histories_,prompt:o.prompt,dispatch:o.dispatch,request:this.semaphore_===null?d:async(s,l)=>{await this.semaphore_.acquire();try{return await d(s,l)}finally{this.semaphore_.release().catch(()=>{})}}}}on(o,d){return U(this.listeners_,o,()=>new Set).add(d),this}off(o,d){const s=this.listeners_.get(o);return s!==void 0&&(s.delete(d),s.size===0&&this.listeners_.delete(o)),this}async dispatch(o){const d=this.listeners_.get(o.type);d!==void 0&&await Promise.all(Array.from(d).map(async s=>{try{await s(o)}catch{}}))}}class L{constructor(){this.articles=[]}index(){return this.articles}create(o){const d={id:$(),title:o.input.title,body:o.input.body,thumbnail:o.input.thumbnail,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return this.articles.push(d),d}update(o){const d=this.articles.find(s=>s.id===o.id);if(d===void 0)throw new Error("Unable to find the matched article.");o.input.title!==void 0&&(d.title=o.input.title),o.input.body!==void 0&&(d.body=o.input.body),o.input.thumbnail!==void 0&&(d.thumbnail=o.input.thumbnail),d.updated_at=new Date().toISOString()}erase(o){const d=this.articles.findIndex(s=>s.id===o.id);if(d===-1)throw new Error("Unable to find the matched article.");this.articles.splice(d,1)}}const O={chatgpt:{model:"chatgpt",options:{reference:!0,strict:!1,separate:null},functions:[{name:"index",parameters:{type:"object",properties:{},additionalProperties:!1,required:[],$defs:{IBbsArticle:{description:"Article entity.\n\n`IBbsArticle` is an entity representing an article in the BBS (Bulletin Board System).",type:"object",properties:{id:{description:`Primary Key.
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
@format uuid`,type:"string"},created_at:{description:`Creation time of the article.
|