(()=>{"use strict";var e={d:(t,s)=>{for(var a in s)e.o(s,a)&&!e.o(t,a)&&Object.defineProperty(t,a,{enumerable:!0,get:s[a]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{fetchServicesAssistantMessagesOpenAi:()=>d});const s=window.wp.i18n,a=window.aicp.helpers,i=window.aicp["api-services"],n=window.aicp["api-transactions"],o=window.aicp["api-assistants"];class r extends Error{constructor(e){super(`Invalid Assistant Message Open AI mode: ${e}`),this.name="InvalidAssistantMessagesOpenAIModeError"}}const{QUADLAYERS_AICP_API_ASSISTANT_MESSAGES_REST_ROUTES:c}=aicpApiAssistantMessages,p=async(e,t)=>{switch(e){case"create":return await(({data:e})=>(0,a.apiFetch)({path:c.assistants_messages,data:e,method:"POST"}))({data:t});case"messages":return await(({data:e})=>(0,a.apiFetch)({path:`${c.assistants_messages}${(0,a.buildParams)(e)}`,method:"GET"}))({data:t});default:throw new r(e)}},d=async(e,t)=>{try{const c=((e,t)=>{switch(e){case"create":return t;case"messages":return{message_openai_before:t.openai_id,limit:1,...t};default:throw new r(e)}})(e,t);let d,l,_=0;const w=5;do{++_;const t=await p(e,{...c,run_openai_id:l?.run_openai_id});if(d=(0,a.handleFrontendApiResponse)(t),l=t,l.run_openai_id&&_>=w)throw new Error((0,s.__)("Max attempts reached. Please try again later.","ai-copilot"))}while(l.run_openai_id&&_<w);if(!d)throw new Error(`${l?.code} ${l?.message}`);if("create"===e){const e=await(0,o.fetchRestApiAssistants)({method:"GET",assistant_id:t.assistant_id}),{model:s,assistant_label:a}=e,{prompt_tokens:r,completion_tokens:c}=l.usage,p=(0,i.calculateTextCost)({model:s,prompt_tokens:r,completion_tokens:c}),d={input:r,output:c},_={consumer_module:"chatbots",api_type:`assistant ${a}`,api_service:"openai",api_service_model:s};return{response:l,transaction:await(0,n.getTransactionCost)(_,p,d)}}return l}catch(e){return console.error(e),null}};(window.aicp=window.aicp||{})["api-assistant-messages"]=t})();