@epam/statgpt-dial-toolkit 0.7.0-dev.20 → 0.7.0-dev.21

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.
Files changed (4) hide show
  1. package/index.cjs +3 -3
  2. package/index.mjs +550 -640
  3. package/package.json +2 -2
  4. package/LICENSE +0 -21
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("@epam/statgpt-shared-toolkit"),m="v1",T=`/${m}/ops/resource/share`,u={VERSION:`/${m}`,BUCKET:`/${m}/bucket`,CONVERSATIONS:`/${m}/metadata/conversations`,CONVERSATION_BY_ID:r=>`/${m}/metadata/conversations/${r}`,CHAT:r=>`/openai/deployments/${r}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:r=>`/${m}/deployments/${r}/configuration`,DATASETS_METADATA:r=>`/v1/deployments/${r}/route/metadata/datasets`,PYTHON_ATTACHMENT:r=>`/v1/deployments/${r}/route/python-attachment`,SHARE_CONVERSATION:`${T}/create`,SHARE_CONVERSATION_ACCEPT:r=>`/${m}/invitations/${r}?accept=true`,SHARE_CONVERSATION_DETAILS:r=>`/${m}/invitations/${r}`,SHARE_CONVERSATION_LIST:`${T}/list`,SHARE_CONVERSATION_DISCARD:`${T}/discard`,SHARE_CONVERSATION_REVOKE:`${T}/revoke`,RATE:r=>`/${m}/${r}/rate`,RENAME:`/${m}/ops/resource/move`},M={LENGTH:"length",STOP:"stop"},_={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},H={CONTENT_FILTER:"content_filter",500:"500"},U={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},x=[_.MINUTE,_.DAILY,_.WEEKLY,_.MONTHLY],V="statgpt",A={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(r=>(r.CONVERSATION="CONVERSATION",r))(O||{}),g=(r=>(r.ME="me",r.OTHERS="others",r))(g||{}),C=(r=>(r.CSV="text/csv",r.TABLE="application/dial-ttyd-table",r.PLOTLY="application/vnd.plotly.v1+json",r.MARKDOWN="text/markdown",r.JSON="application/json",r.JPEG="image/jpeg",r.PNG="image/png",r.CROSS_DATASET_GRID="cross_dataset_grid",r.CUSTOM_DATA_GRID="custom_data_grid",r.CUSTOM_CHART="custom_chart",r.CUSTOM_CODE_SAMPLE="custom_code_sample",r))(C||{}),y=(r=>(r.LINK="link",r))(y||{});const P=r=>r.content?(console.info(`Using direct content format: ${r.content}`),r.content):r.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${r.choices[0].delta.content}`),r.choices[0].delta.content):r.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${r.choices[0].message.content}`),r.choices[0].message.content):(console.info("Unknown SSE data format:",r),null),N=(r,t,n)=>{if(t?.(r),n){const e=P(r);e&&n(e)}},$=(r,t)=>r.error||r.message||`${t.status} ${t.statusText}`,F=(r,t)=>{const n=r?.reduce((e,o)=>(e[o.index]=o,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},k=(r,t)=>{const n=structuredClone(r);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&K(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=F(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function K(r,t){if(t.content){const n=j(t.content);n!=null?r.content=r.content.slice(0,-n):r.content=`${r.content||""}${t.content}`}}function j(r){const t=r.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const v=r=>{const t=r.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):r.name;return{modelId:t[0],conversationName:n}},w=r=>{const t=Date.now(),n=l.getClearedConversationName(r.name);return`${r.folderId}/${n}-${t}`},Y=r=>({resourceTypes:[O.CONVERSATION],with:r}),p=async(r,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(r,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function R(r){return r.split("/").map(t=>encodeURIComponent(t)).join("/")}function G(r){return r.split("/").map(t=>decodeURIComponent(t)).join("/")}function D(r){if(r?.kind!==A.RATE_LIMIT||typeof r.retryAfterSeconds!="number")return null;const t=new Date(r.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+r.retryAfterSeconds*1e3)}function B(r,t=Date.now()){const n=D(r);return n?n.getTime()>t:!1}function J(r,t="en-GB"){return{date:r.toLocaleDateString(t),time:r.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class L{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},o){const{onMessage:s,onError:a,onComplete:i,signal:c}=e;try{const d=await this.initializeStreamRequest(t,n,c,o);await this.processStreamData(d,s),i?.()}catch(d){this.handleStreamError(d,a)}}async initializeStreamRequest(t,n,e,o){const s=l.getHeaders(void 0,{jwt:o}),a=await p(t,{Accept:"text/event-stream",...s},{method:"POST",body:n,signal:e});if(!a.ok){const i=await a.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new l.HttpError({status:a.status,message:c.error??"No response body"})}if(!a.body)throw new l.HttpError({message:"No response body",status:a.status});return a.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:o,value:s}=await t.read();if(o){e.trim()&&this.parseSSEDataLine(e,n);break}const a=this.decoder.decode(s,{stream:!0});e+=a;const i=e.split(`
2
- `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,n)}}finally{t.releaseLock()}}handleStreamError(t,n){const e=t instanceof Error?t:new Error(String(t));throw n?.(e),e}parseSSEDataLine(t,n){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const o=e.slice(6);if(o==="[DONE]"){console.info("SSE: Stream completed");return}let s;try{s=JSON.parse(o)}catch(a){console.error(`Failed to parse SSE data: ${o} ${a}`)}n?.(s)}}}const q=new L,W=async(r,t,n,e,o)=>{const{onMessage:s,onToken:a,onComplete:i,onError:c,model:d,signal:S}=n,I={conversationId:r,messages:t,model:d,custom_fields:o};await q.streamChat(l.API_ROUTES.CHAT,I,{onMessage:b=>N(b,s,a),onComplete:i,onError:c,signal:S},e)},E=r=>r instanceof Error&&r.message.includes("404"),f=r=>`/v1/conversations/${R(r)}`;function h(r){console.warn("[ConversationApi] suppressed error, returning empty result",r)}class X{constructor(t){this.client=t}async getConversations(t,n,e){const o=`${n?e?`${n}/${e}`:`${n}`:""}`,s=`${u.CONVERSATIONS}/${o}`;try{return(await this.client.getRequest(s+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:d}=v(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:o,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:d,name:d}}})}catch(a){if(E(a))return h({endpoint:s,error:a}),[];throw a}}async getConversation(t,n){try{return await this.client.getRequest(f(t),n)}catch(e){if(E(e))return h({endpoint:f(t),error:e}),null;throw e}}async getFile(t,n){try{const e=`${u.VERSION}/${R(t)}`;return await this.client.getRequest(e,n)}catch(e){if(E(e))return h({filePath:t,error:e}),null;throw e}}async putOnboardingFile(t,n,e,o){try{const s=`${u.VERSION}/${R(n)}`,a="----NodeMultipartBoundary",c=[`--${a}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${a}--`,""].join(`\r
3
- `);return await this.client.request(s,o,{method:"PUT",body:c,headers:l.getMultipartHeaders(a),isFormData:!0})}catch(s){if(E(s))return h({filePath:n,error:s}),null;throw s}}async getOnboardingFile(t,n){try{const e=`${u.VERSION}/${R(t)}`;return await this.client.getRequest(e,n)}catch(e){if(E(e))return h({filePath:t,error:e}),null;throw e}}async getFileBlob(t,n){try{const e=`${u.VERSION}/${R(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(E(e))return h({filePath:t,error:e}),null;throw e}}async deleteFile(t,n){try{const e=`${u.VERSION}/${R(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(E(e)){h({filePath:t,error:e});return}throw e}}async putFile(t,n,e){try{const o=`${u.VERSION}/${R(t)}`,s=new FormData,a=decodeURIComponent(t.split("/").at(-1)??"file");s.append("attachment",n,a),await this.client.request(o,e,{method:"PUT",body:s,isFormData:!0})}catch(o){if(E(o)){h({filePath:t,error:o});return}throw o}}async createConversation(t,n){const e=t?.id||w(t),{name:o,folderId:s,model:a,messages:i,custom_fields:c}=t,d={id:e,name:o,folderId:s,model:a,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(f(e),n,{method:"PUT",body:d}),{id:e,name:o,folderId:s,model:a,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,n){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:n})}async getSharedConversations(t,n){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:n})}async revokeSharedConversations(t,n){await this.client.postRequest(u.SHARE_CONVERSATION_REVOKE,t,{body:n})}async updateConversation(t,n,e){const o=await this.getConversation(t,e);if(!o)throw new Error(`Conversation with id ${t} not found`);const s={...o,...n,updatedAt:Date.now()};return await this.client.request(f(t),e,{method:"PUT",body:s})}async deleteConversation(t,n,e){n?.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:n?.url}]}}):await this.client.request(f(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,o=encodeURIComponent(e),s=`${u.CHAT(o)}?api-version=${this.client.config.version}`,a={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(s,n,{method:"POST",body:a,chatReference:t.conversationId})}async rateResponse(t,n,e,o){return await this.client.postRequest(u.RATE(t),o,{body:{responseId:n,rate:e}})}async renameConversation(t,n,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:n,overwrite:!0}})}}class z{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,n,e){return this.request(t,n,{...e,method:"GET"})}async postRequest(t,n,e){return this.request(t,n,{...e,method:"POST"})}async requestBlob(t,n,e){const o=`${this.config.host}${t}`,s={...l.getHeaders(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};try{return(await p(o,s,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:o,error:a instanceof Error?a.message:String(a)}),a}}async request(t,n,e){const o=Date.now(),s=`${this.config.host}${t}`,a={...l.getHeaders(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",s,e,a);try{const i=await p(s,a,e),c=Date.now()-o;let d;const S=await i.text();try{d=S?JSON.parse(S):{}}catch{if(this.addErrorRequestParsing(s,e,i,c,S),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${S.substring(0,100)}`);d={data:S}}if(!i.ok){this.addErrorRequestLog(s,e,i,c,d);const I=$(d,i);throw new Error(`API request failed: ${I}`)}return d}catch(i){const c=Date.now()-o;throw console.error("API Request Exception",{method:e.method,url:s,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const o=`${this.config.host}${t}`,s=l.getHeaders(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},e.headers);this.addInfoRequestLog("Stream Request",o,e,s);const a=await p(o,s,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:o,status:a.status,statusText:a.statusText}),new Error(`Stream request failed: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("No response body for stream");return a.body}addInfoRequestLog(t,n,e,o){const s={method:e.method||"GET",url:n,headers:l.sanitizeHeaders(o)};e.body&&(s.body=e.body),console.info(t,s)}addErrorRequestLog(t,n,e,o,s){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${o}ms`,response:s})}addErrorRequestParsing(t,n,e,o,s){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${o}ms`,responseText:s.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=C;exports.COMPLETION_FINISH_REASON=M;exports.CUSTOM_VIEW_STATE_KEY=V;exports.ChatStreamSSEClient=L;exports.ConversationApi=X;exports.DIAL_API_ROUTES=u;exports.DIAL_ERROR_CODES=H;exports.DIAL_ERROR_TYPES=U;exports.DialApiClient=z;exports.ERROR_CONTEXT_KIND=A;exports.EXCEEDED_LIMIT=_;exports.EXCEEDED_LIMIT_ORDER=x;exports.InvitationType=y;exports.ResourceTypes=O;exports.ShareTarget=g;exports.chatStreamSSEClient=q;exports.decodeApiUrl=G;exports.encodeApiUrl=R;exports.formatDateTime=J;exports.generateConversationId=w;exports.getErrorMessage=$;exports.getRateLimitRestoreDate=D;exports.getSharedConversationsRequest=Y;exports.handleStreamMessage=N;exports.isRateLimitStillActive=B;exports.mergeMessages=k;exports.parseConversationName=v;exports.sendRequest=p;exports.streamChatResponse=W;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@epam/statgpt-shared-toolkit");var t=`v1`,n=`/${t}/ops/resource/share`,r={VERSION:`/${t}`,BUCKET:`/${t}/bucket`,CONVERSATIONS:`/${t}/metadata/conversations`,CONVERSATION_BY_ID:e=>`/${t}/metadata/conversations/${e}`,CHAT:e=>`/openai/deployments/${e}/chat/completions`,MODELS:`/openai/models`,CONFIGURATION:e=>`/${t}/deployments/${e}/configuration`,DATASETS_METADATA:e=>`/v1/deployments/${e}/route/metadata/datasets`,PYTHON_ATTACHMENT:e=>`/v1/deployments/${e}/route/python-attachment`,SHARE_CONVERSATION:`${n}/create`,SHARE_CONVERSATION_ACCEPT:e=>`/${t}/invitations/${e}?accept=true`,SHARE_CONVERSATION_DETAILS:e=>`/${t}/invitations/${e}`,SHARE_CONVERSATION_LIST:`${n}/list`,SHARE_CONVERSATION_DISCARD:`${n}/discard`,SHARE_CONVERSATION_REVOKE:`${n}/revoke`,RATE:e=>`/${t}/${e}/rate`,RENAME:`/${t}/ops/resource/move`},i={LENGTH:`length`,STOP:`stop`},a={MINUTE:`minute`,DAILY:`daily`,WEEKLY:`weekly`,MONTHLY:`monthly`},o={CONTENT_FILTER:`content_filter`,500:`500`},s={RUNTIME_ERROR:`runtime_error`,RATE_LIMIT_EXCEEDED:`rate_limit_exceeded`},c=[a.MINUTE,a.DAILY,a.WEEKLY,a.MONTHLY],l=`statgpt`,u={RATE_LIMIT:`rate_limit`,UNKNOWN:`unknown`},d=function(e){return e.CONVERSATION=`CONVERSATION`,e}({}),f=function(e){return e.ME=`me`,e.OTHERS=`others`,e}({}),p=function(e){return e.CSV=`text/csv`,e.TABLE=`application/dial-ttyd-table`,e.PLOTLY=`application/vnd.plotly.v1+json`,e.MARKDOWN=`text/markdown`,e.JSON=`application/json`,e.JPEG=`image/jpeg`,e.PNG=`image/png`,e.CROSS_DATASET_GRID=`cross_dataset_grid`,e.CUSTOM_DATA_GRID=`custom_data_grid`,e.CUSTOM_CHART=`custom_chart`,e.CUSTOM_CODE_SAMPLE=`custom_code_sample`,e}({}),m=function(e){return e.LINK=`link`,e}({}),h=e=>e.content?(console.info(`Using direct content format: ${e.content}`),e.content):e.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${e.choices[0].delta.content}`),e.choices[0].delta.content):e.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${e.choices[0].message.content}`),e.choices[0].message.content):(console.info(`Unknown SSE data format:`,e),null),g=(e,t,n)=>{if(t?.(e),n){let t=h(e);t&&n(t)}},_=(e,t)=>e.error||e.message||`${t.status} ${t.statusText}`,v=(e,t)=>{let n=e?.reduce((e,t)=>(e[t.index]=t,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||``)+e.content),e.name&&(n[e.index].name=(n[e.index].name||``)+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},y=(e,t)=>{let n=structuredClone(e);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&b(n,e),e.custom_content&&(n.custom_content||={},e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=v(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function b(e,t){if(t.content){let n=x(t.content);n==null?e.content=`${e.content||``}${t.content}`:e.content=e.content.slice(0,-n)}}function x(e){let t=e.match(/delete_chars\((\d+)\)/);return t==null?null:parseInt(t[1],10)}var S=e=>{let t=e.name?.split(`__`)||[],n=t.length>1?t.slice(1).join(`__`):e.name;return{modelId:t[0],conversationName:n}},C=t=>{let n=Date.now(),r=(0,e.getClearedConversationName)(t.name);return`${t.folderId}/${r}-${n}`},w=e=>({resourceTypes:[d.CONVERSATION],with:e}),T=async(e,t,n)=>{let r=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(e,{method:n.method||`GET`,headers:t,body:r,signal:n?.signal})};function E(e){return e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}function D(e){return e.split(`/`).map(e=>decodeURIComponent(e)).join(`/`)}function O(e){if(e?.kind!==u.RATE_LIMIT||typeof e.retryAfterSeconds!=`number`)return null;let t=new Date(e.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+e.retryAfterSeconds*1e3)}function k(e,t=Date.now()){let n=O(e);return n?n.getTime()>t:!1}function A(e,t=`en-GB`){return{date:e.toLocaleDateString(t),time:e.toLocaleTimeString(t,{hour:`2-digit`,minute:`2-digit`})}}var j=class{constructor(){this.decoder=new TextDecoder}async streamChat(e,t,n={},r){let{onMessage:i,onError:a,onComplete:o,signal:s}=n;try{let n=await this.initializeStreamRequest(e,t,s,r);await this.processStreamData(n,i),o?.()}catch(e){this.handleStreamError(e,a)}}async initializeStreamRequest(t,n,r,i){let a=await T(t,{Accept:`text/event-stream`,...(0,e.getHeaders)(void 0,{jwt:i})},{method:`POST`,body:n,signal:r});if(!a.ok){let t=await a.text(),n={};try{n=JSON.parse(t)}catch{n.error=`Failed to parse error body`}throw new e.HttpError({status:a.status,message:n.error??`No response body`})}if(!a.body)throw new e.HttpError({message:`No response body`,status:a.status});return a.body.getReader()}async processStreamData(e,t){let n=``;try{for(;;){let{done:r,value:i}=await e.read();if(r){n.trim()&&this.parseSSEDataLine(n,t);break}let a=this.decoder.decode(i,{stream:!0});n+=a;let o=n.split(`
2
+ `);n=o.pop()||``;for(let e of o)this.parseSSEDataLine(e,t)}}finally{e.releaseLock()}}handleStreamError(e,t){let n=e instanceof Error?e:Error(String(e));throw t?.(n),n}parseSSEDataLine(e,t){let n=e.trim();if(!(!n||n.startsWith(`:`))&&n.startsWith(`data: `)){let e=n.slice(6);if(e===`[DONE]`){console.info(`SSE: Stream completed`);return}let r;try{r=JSON.parse(e)}catch(t){console.error(`Failed to parse SSE data: ${e} ${t}`)}t?.(r)}}},M=new j,N=async(t,n,r,i,a)=>{let{onMessage:o,onToken:s,onComplete:c,onError:l,model:u,signal:d}=r,f={conversationId:t,messages:n,model:u,custom_fields:a};await M.streamChat(e.API_ROUTES.CHAT,f,{onMessage:e=>g(e,o,s),onComplete:c,onError:l,signal:d},i)},P=e=>e instanceof Error&&e.message.includes(`404`),F=e=>`/v1/conversations/${E(e)}`;function I(e){console.warn(`[ConversationApi] suppressed error, returning empty result`,e)}var L=class{constructor(e){this.client=e}async getConversations(e,t,n){let i=`${t?n?`${t}/${n}`:`${t}`:``}`,a=`${r.CONVERSATIONS}/${i}`;try{return(await this.client.getRequest(a+`/?limit=1000&recursive=false`,e).then(e=>e.items||[])).map(e=>{let{conversationName:t,modelId:n}=S(e);return{id:e.url?.replace(`conversations/`,``)||e.name,name:t,folderId:i,createdAt:e.createdAt,updatedAt:e.updatedAt,model:{id:n,name:n}}})}catch(e){if(P(e))return I({endpoint:a,error:e}),[];throw e}}async getConversation(e,t){try{return await this.client.getRequest(F(e),t)}catch(t){if(P(t))return I({endpoint:F(e),error:t}),null;throw t}}async getFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.getRequest(n,t)}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async putOnboardingFile(t,n,i,a){try{let o=`${r.VERSION}/${E(n)}`,s=`----NodeMultipartBoundary`,c=[`--${s}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,`Content-Type: application/json`,``,JSON.stringify(i),`--${s}--`,``].join(`\r
3
+ `);return await this.client.request(o,a,{method:`PUT`,body:c,headers:(0,e.getMultipartHeaders)(s),isFormData:!0})}catch(e){if(P(e))return I({filePath:n,error:e}),null;throw e}}async getOnboardingFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.getRequest(n,t)}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async getFileBlob(e,t){try{let n=`${r.VERSION}/${E(e)}`;return await this.client.requestBlob(n,t,{method:`GET`})}catch(t){if(P(t))return I({filePath:e,error:t}),null;throw t}}async deleteFile(e,t){try{let n=`${r.VERSION}/${E(e)}`;await this.client.request(n,t,{method:`DELETE`})}catch(t){if(P(t)){I({filePath:e,error:t});return}throw t}}async putFile(e,t,n){try{let i=`${r.VERSION}/${E(e)}`,a=new FormData,o=decodeURIComponent(e.split(`/`).at(-1)??`file`);a.append(`attachment`,t,o),await this.client.request(i,n,{method:`PUT`,body:a,isFormData:!0})}catch(t){if(P(t)){I({filePath:e,error:t});return}throw t}}async createConversation(e,t){let n=e?.id||C(e),{name:r,folderId:i,model:a,messages:o,custom_fields:s}=e,c={id:n,name:r,folderId:i,model:a,messages:o||[],selectedAddons:e.selectedAddons||[],prompt:e.prompt||``,temperature:e.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:s};return await this.client.request(F(n),t,{method:`PUT`,body:c}),{id:n,name:r,folderId:i,model:a,createdAt:c.createdAt,updatedAt:c.updatedAt}}async generateConversationLink(e,t){return await this.client.postRequest(r.SHARE_CONVERSATION,e,{body:t})}async getSharedConversations(e,t){return await this.client.postRequest(r.SHARE_CONVERSATION_LIST,e,{body:t})}async revokeSharedConversations(e,t){await this.client.postRequest(r.SHARE_CONVERSATION_REVOKE,e,{body:t})}async updateConversation(e,t,n){let r=await this.getConversation(e,n);if(!r)throw Error(`Conversation with id ${e} not found`);let i={...r,...t,updatedAt:Date.now()};return await this.client.request(F(e),n,{method:`PUT`,body:i})}async deleteConversation(e,t,n){t?.isShared?await this.client.postRequest(r.SHARE_CONVERSATION_DISCARD,n,{body:{resources:[{url:t?.url}]}}):await this.client.request(F(decodeURI(e)),n,{method:`DELETE`})}async streamChat(e,t){let n=e.model.id,i=encodeURIComponent(n),a=`${r.CHAT(i)}?api-version=${this.client.config.version}`,o={messages:e.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:e.custom_fields};return await this.client.stream(a,t,{method:`POST`,body:o,chatReference:e.conversationId})}async rateResponse(e,t,n,i){return await this.client.postRequest(r.RATE(e),i,{body:{responseId:t,rate:n}})}async renameConversation(e,t,n){return await this.client.postRequest(r.RENAME,n,{body:{sourceUrl:e,destinationUrl:t,overwrite:!0}})}},R=class{constructor(e){this.config=e,console.info(`DialApiClient initialized`,{host:e.host||`NOT SET`,hasApiKey:!!e.apiKey,version:e.version})}async getRequest(e,t,n){return this.request(e,t,{...n,method:`GET`})}async postRequest(e,t,n){return this.request(e,t,{...n,method:`POST`})}async requestBlob(t,n,r){let i=`${this.config.host}${t}`,a={...(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0}),...r.headers};try{return(await T(i,a,r)).blob()}catch(e){throw console.error(`API Request Exception`,{method:r.method,url:i,error:e instanceof Error?e.message:String(e)}),e}}async request(t,n,r){let i=Date.now(),a=`${this.config.host}${t}`,o={...(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0}),...r.headers};this.addInfoRequestLog(`API Request`,a,r,o);try{let e=await T(a,o,r),t=Date.now()-i,n,s=await e.text();try{n=s?JSON.parse(s):{}}catch{if(this.addErrorRequestParsing(a,r,e,t,s),!e.ok)throw Error(`API request failed: ${e.status} ${e.statusText} - ${s.substring(0,100)}`);n={data:s}}if(!e.ok){this.addErrorRequestLog(a,r,e,t,n);let i=_(n,e);throw Error(`API request failed: ${i}`)}return n}catch(e){let t=Date.now()-i;throw console.error(`API Request Exception`,{method:r.method,url:a,duration:`${t}ms`,error:e instanceof Error?e.message:String(e)}),e}}async stream(t,n,r){let i=`${this.config.host}${t}`,a=(0,e.getHeaders)(this.config.apiKey,{jwt:n,chatReference:r.chatReference,contentType:r.isFormData?null:void 0},r.headers);this.addInfoRequestLog(`Stream Request`,i,r,a);let o=await T(i,a,r);if(!o.ok)throw console.error(`Stream Request Failed`,{method:r.method||`POST`,url:i,status:o.status,statusText:o.statusText}),Error(`Stream request failed: ${o.status} ${o.statusText}`);if(!o.body)throw Error(`No response body for stream`);return o.body}addInfoRequestLog(t,n,r,i){let a={method:r.method||`GET`,url:n,headers:(0,e.sanitizeHeaders)(i)};r.body&&(a.body=r.body),console.info(t,a)}addErrorRequestLog(e,t,n,r,i){console.error(`API Request Failed`,{method:t.method,url:e,status:n.status,statusText:n.statusText,duration:`${r}ms`,response:i})}addErrorRequestParsing(e,t,n,r,i){console.error(`API Response Parse Error`,{method:t.method,url:e,status:n.status,statusText:n.statusText,duration:`${r}ms`,responseText:i.substring(0,200),error:`Response is not valid JSON`})}};exports.AttachmentType=p,exports.COMPLETION_FINISH_REASON=i,exports.CUSTOM_VIEW_STATE_KEY=l,exports.ChatStreamSSEClient=j,exports.ConversationApi=L,exports.DIAL_API_ROUTES=r,exports.DIAL_ERROR_CODES=o,exports.DIAL_ERROR_TYPES=s,exports.DialApiClient=R,exports.ERROR_CONTEXT_KIND=u,exports.EXCEEDED_LIMIT=a,exports.EXCEEDED_LIMIT_ORDER=c,exports.InvitationType=m,exports.ResourceTypes=d,exports.ShareTarget=f,exports.chatStreamSSEClient=M,exports.decodeApiUrl=D,exports.encodeApiUrl=E,exports.formatDateTime=A,exports.generateConversationId=C,exports.getErrorMessage=_,exports.getRateLimitRestoreDate=O,exports.getSharedConversationsRequest=w,exports.handleStreamMessage=g,exports.isRateLimitStillActive=k,exports.mergeMessages=y,exports.parseConversationName=S,exports.sendRequest=T,exports.streamChatResponse=N;
package/index.mjs CHANGED
@@ -1,651 +1,561 @@
1
- import { getClearedConversationName as N, getHeaders as _, HttpError as O, API_ROUTES as g, getMultipartHeaders as C, sanitizeHeaders as $ } from "@epam/statgpt-shared-toolkit";
2
- const m = "v1", S = `/${m}/ops/resource/share`, u = {
3
- VERSION: `/${m}`,
4
- BUCKET: `/${m}/bucket`,
5
- CONVERSATIONS: `/${m}/metadata/conversations`,
6
- CONVERSATION_BY_ID: (o) => `/${m}/metadata/conversations/${o}`,
7
- CHAT: (o) => `/openai/deployments/${o}/chat/completions`,
8
- MODELS: "/openai/models",
9
- CONFIGURATION: (o) => `/${m}/deployments/${o}/configuration`,
10
- DATASETS_METADATA: (o) => `/v1/deployments/${o}/route/metadata/datasets`,
11
- PYTHON_ATTACHMENT: (o) => `/v1/deployments/${o}/route/python-attachment`,
12
- SHARE_CONVERSATION: `${S}/create`,
13
- SHARE_CONVERSATION_ACCEPT: (o) => `/${m}/invitations/${o}?accept=true`,
14
- SHARE_CONVERSATION_DETAILS: (o) => `/${m}/invitations/${o}`,
15
- SHARE_CONVERSATION_LIST: `${S}/list`,
16
- SHARE_CONVERSATION_DISCARD: `${S}/discard`,
17
- SHARE_CONVERSATION_REVOKE: `${S}/revoke`,
18
- RATE: (o) => `/${m}/${o}/rate`,
19
- RENAME: `/${m}/ops/resource/move`
20
- }, G = {
21
- LENGTH: "length",
22
- STOP: "stop"
23
- }, p = {
24
- MINUTE: "minute",
25
- DAILY: "daily",
26
- WEEKLY: "weekly",
27
- MONTHLY: "monthly"
28
- }, Y = {
29
- CONTENT_FILTER: "content_filter",
30
- 500: "500"
31
- }, B = {
32
- RUNTIME_ERROR: "runtime_error",
33
- RATE_LIMIT_EXCEEDED: "rate_limit_exceeded"
34
- }, J = [
35
- p.MINUTE,
36
- p.DAILY,
37
- p.WEEKLY,
38
- p.MONTHLY
39
- ], W = "statgpt", v = {
40
- RATE_LIMIT: "rate_limit",
41
- UNKNOWN: "unknown"
1
+ import { API_ROUTES as e, HttpError as t, getClearedConversationName as n, getHeaders as r, getMultipartHeaders as i, sanitizeHeaders as a } from "@epam/statgpt-shared-toolkit";
2
+ //#region libs/dial-toolkit/src/constants/api-urls.ts
3
+ var o = "v1", s = `/${o}/ops/resource/share`, c = {
4
+ VERSION: `/${o}`,
5
+ BUCKET: `/${o}/bucket`,
6
+ CONVERSATIONS: `/${o}/metadata/conversations`,
7
+ CONVERSATION_BY_ID: (e) => `/${o}/metadata/conversations/${e}`,
8
+ CHAT: (e) => `/openai/deployments/${e}/chat/completions`,
9
+ MODELS: "/openai/models",
10
+ CONFIGURATION: (e) => `/${o}/deployments/${e}/configuration`,
11
+ DATASETS_METADATA: (e) => `/v1/deployments/${e}/route/metadata/datasets`,
12
+ PYTHON_ATTACHMENT: (e) => `/v1/deployments/${e}/route/python-attachment`,
13
+ SHARE_CONVERSATION: `${s}/create`,
14
+ SHARE_CONVERSATION_ACCEPT: (e) => `/${o}/invitations/${e}?accept=true`,
15
+ SHARE_CONVERSATION_DETAILS: (e) => `/${o}/invitations/${e}`,
16
+ SHARE_CONVERSATION_LIST: `${s}/list`,
17
+ SHARE_CONVERSATION_DISCARD: `${s}/discard`,
18
+ SHARE_CONVERSATION_REVOKE: `${s}/revoke`,
19
+ RATE: (e) => `/${o}/${e}/rate`,
20
+ RENAME: `/${o}/ops/resource/move`
21
+ }, l = {
22
+ LENGTH: "length",
23
+ STOP: "stop"
24
+ }, u = {
25
+ MINUTE: "minute",
26
+ DAILY: "daily",
27
+ WEEKLY: "weekly",
28
+ MONTHLY: "monthly"
29
+ }, d = {
30
+ CONTENT_FILTER: "content_filter",
31
+ 500: "500"
32
+ }, f = {
33
+ RUNTIME_ERROR: "runtime_error",
34
+ RATE_LIMIT_EXCEEDED: "rate_limit_exceeded"
35
+ }, p = [
36
+ u.MINUTE,
37
+ u.DAILY,
38
+ u.WEEKLY,
39
+ u.MONTHLY
40
+ ], m = "statgpt", h = {
41
+ RATE_LIMIT: "rate_limit",
42
+ UNKNOWN: "unknown"
43
+ }, g = /* @__PURE__ */ function(e) {
44
+ return e.CONVERSATION = "CONVERSATION", e;
45
+ }({}), _ = /* @__PURE__ */ function(e) {
46
+ return e.ME = "me", e.OTHERS = "others", e;
47
+ }({}), v = /* @__PURE__ */ function(e) {
48
+ return e.CSV = "text/csv", e.TABLE = "application/dial-ttyd-table", e.PLOTLY = "application/vnd.plotly.v1+json", e.MARKDOWN = "text/markdown", e.JSON = "application/json", e.JPEG = "image/jpeg", e.PNG = "image/png", e.CROSS_DATASET_GRID = "cross_dataset_grid", e.CUSTOM_DATA_GRID = "custom_data_grid", e.CUSTOM_CHART = "custom_chart", e.CUSTOM_CODE_SAMPLE = "custom_code_sample", e;
49
+ }({}), y = /* @__PURE__ */ function(e) {
50
+ return e.LINK = "link", e;
51
+ }({}), b = (e) => e.content ? (console.info(`Using direct content format: ${e.content}`), e.content) : e.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${e.choices[0].delta.content}`), e.choices[0].delta.content) : e.choices?.[0]?.message?.content ? (console.info(`Using complete message format: ${e.choices[0].message.content}`), e.choices[0].message.content) : (console.info("Unknown SSE data format:", e), null), x = (e, t, n) => {
52
+ if (t?.(e), n) {
53
+ let t = b(e);
54
+ t && n(t);
55
+ }
56
+ }, S = (e, t) => e.error || e.message || `${t.status} ${t.statusText}`, C = (e, t) => {
57
+ let n = e?.reduce((e, t) => (e[t.index] = t, e), {});
58
+ return t.forEach((e) => {
59
+ n[e.index] ? (e.attachments && (n[e.index].attachments = (n[e.index].attachments || []).concat(e.attachments)), e.content && (n[e.index].content = (n[e.index].content || "") + e.content), e.name && (n[e.index].name = (n[e.index].name || "") + e.name), e.status && (n[e.index].status = e.status)) : n[e.index] = e;
60
+ }), Object.values(n);
61
+ }, w = (e, t) => {
62
+ let n = structuredClone(e);
63
+ return t.forEach((e) => {
64
+ e.errorMessage && (n.errorMessage = e.errorMessage), e.role && (n.role = e.role), e.responseId && (n.responseId = e.responseId), e.content && T(n, e), e.custom_content && (n.custom_content ||= {}, e.custom_content.attachments && (n.custom_content.attachments || (n.custom_content.attachments = []), n.custom_content.attachments = n.custom_content.attachments.concat(e.custom_content.attachments)), e.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = C(n.custom_content.stages, e.custom_content.stages)), e.custom_content.state && (n.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (n.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (n.custom_content.form_value = e.custom_content.form_value));
65
+ }), n;
42
66
  };
43
- var A = /* @__PURE__ */ ((o) => (o.CONVERSATION = "CONVERSATION", o))(A || {}), w = /* @__PURE__ */ ((o) => (o.ME = "me", o.OTHERS = "others", o))(w || {}), q = /* @__PURE__ */ ((o) => (o.CSV = "text/csv", o.TABLE = "application/dial-ttyd-table", o.PLOTLY = "application/vnd.plotly.v1+json", o.MARKDOWN = "text/markdown", o.JSON = "application/json", o.JPEG = "image/jpeg", o.PNG = "image/png", o.CROSS_DATASET_GRID = "cross_dataset_grid", o.CUSTOM_DATA_GRID = "custom_data_grid", o.CUSTOM_CHART = "custom_chart", o.CUSTOM_CODE_SAMPLE = "custom_code_sample", o))(q || {}), D = /* @__PURE__ */ ((o) => (o.LINK = "link", o))(D || {});
44
- const b = (o) => o.content ? (console.info(`Using direct content format: ${o.content}`), o.content) : o.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${o.choices[0].delta.content}`), o.choices[0].delta.content) : o.choices?.[0]?.message?.content ? (console.info(
45
- `Using complete message format: ${o.choices[0].message.content}`
46
- ), o.choices[0].message.content) : (console.info("Unknown SSE data format:", o), null), L = (o, t, n) => {
47
- if (t?.(o), n) {
48
- const e = b(o);
49
- e && n(e);
50
- }
51
- }, M = (o, t) => o.error || o.message || `${t.status} ${t.statusText}`, x = (o, t) => {
52
- const n = o?.reduce(
53
- (e, r) => (e[r.index] = r, e),
54
- {}
55
- );
56
- return t.forEach((e) => {
57
- n[e.index] ? (e.attachments && (n[e.index].attachments = (n[e.index].attachments || []).concat(e.attachments)), e.content && (n[e.index].content = (n[e.index].content || "") + e.content), e.name && (n[e.index].name = (n[e.index].name || "") + e.name), e.status && (n[e.index].status = e.status)) : n[e.index] = e;
58
- }), Object.values(n);
59
- }, z = (o, t) => {
60
- const n = structuredClone(o);
61
- return t.forEach((e) => {
62
- e.errorMessage && (n.errorMessage = e.errorMessage), e.role && (n.role = e.role), e.responseId && (n.responseId = e.responseId), e.content && H(n, e), e.custom_content && (n.custom_content || (n.custom_content = {}), e.custom_content.attachments && (n.custom_content.attachments || (n.custom_content.attachments = []), n.custom_content.attachments = n.custom_content.attachments.concat(
63
- e.custom_content.attachments
64
- )), e.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = x(
65
- n.custom_content.stages,
66
- e.custom_content.stages
67
- )), e.custom_content.state && (n.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (n.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (n.custom_content.form_value = e.custom_content.form_value));
68
- }), n;
69
- };
70
- function H(o, t) {
71
- if (t.content) {
72
- const n = U(t.content);
73
- n != null ? o.content = o.content.slice(0, -n) : o.content = `${o.content || ""}${t.content}`;
74
- }
67
+ function T(e, t) {
68
+ if (t.content) {
69
+ let n = E(t.content);
70
+ n == null ? e.content = `${e.content || ""}${t.content}` : e.content = e.content.slice(0, -n);
71
+ }
75
72
  }
76
- function U(o) {
77
- const t = o.match(/delete_chars\((\d+)\)/);
78
- return t != null ? parseInt(t[1], 10) : null;
73
+ function E(e) {
74
+ let t = e.match(/delete_chars\((\d+)\)/);
75
+ return t == null ? null : parseInt(t[1], 10);
79
76
  }
80
- const V = (o) => {
81
- const t = o.name?.split("__") || [], n = t.length > 1 ? t.slice(1).join("__") : o.name;
82
- return { modelId: t[0], conversationName: n };
83
- }, P = (o) => {
84
- const t = Date.now(), n = N(o.name);
85
- return `${o.folderId}/${n}-${t}`;
86
- }, X = (o) => ({ resourceTypes: [A.CONVERSATION], with: o }), T = async (o, t, n) => {
87
- const e = n?.body === void 0 ? void 0 : n?.isFormData ? n.body : JSON.stringify(n.body);
88
- return await fetch(o, {
89
- method: n.method || "GET",
90
- headers: t,
91
- body: e,
92
- signal: n?.signal
93
- });
77
+ //#endregion
78
+ //#region libs/dial-toolkit/src/utils/parse-conversation-name.ts
79
+ var D = (e) => {
80
+ let t = e.name?.split("__") || [], n = t.length > 1 ? t.slice(1).join("__") : e.name;
81
+ return {
82
+ modelId: t[0],
83
+ conversationName: n
84
+ };
85
+ }, O = (e) => {
86
+ let t = Date.now(), r = n(e.name);
87
+ return `${e.folderId}/${r}-${t}`;
88
+ }, k = (e) => ({
89
+ resourceTypes: [g.CONVERSATION],
90
+ with: e
91
+ }), A = async (e, t, n) => {
92
+ let r = n?.body === void 0 ? void 0 : n?.isFormData ? n.body : JSON.stringify(n.body);
93
+ return await fetch(e, {
94
+ method: n.method || "GET",
95
+ headers: t,
96
+ body: r,
97
+ signal: n?.signal
98
+ });
94
99
  };
95
- function R(o) {
96
- return o.split("/").map((t) => encodeURIComponent(t)).join("/");
97
- }
98
- function Q(o) {
99
- return o.split("/").map((t) => decodeURIComponent(t)).join("/");
100
- }
101
- function F(o) {
102
- if (o?.kind !== v.RATE_LIMIT || typeof o.retryAfterSeconds != "number")
103
- return null;
104
- const t = new Date(o.occurredAt).getTime();
105
- return Number.isNaN(t) ? null : new Date(t + o.retryAfterSeconds * 1e3);
106
- }
107
- function Z(o, t = Date.now()) {
108
- const n = F(o);
109
- return n ? n.getTime() > t : !1;
100
+ //#endregion
101
+ //#region libs/dial-toolkit/src/utils/url.ts
102
+ function j(e) {
103
+ return e.split("/").map((e) => encodeURIComponent(e)).join("/");
110
104
  }
111
- function ee(o, t = "en-GB") {
112
- return {
113
- date: o.toLocaleDateString(t),
114
- time: o.toLocaleTimeString(t, {
115
- hour: "2-digit",
116
- minute: "2-digit"
117
- })
118
- };
105
+ function M(e) {
106
+ return e.split("/").map((e) => decodeURIComponent(e)).join("/");
119
107
  }
120
- class k {
121
- constructor() {
122
- this.decoder = new TextDecoder();
123
- }
124
- async streamChat(t, n, e = {}, r) {
125
- const { onMessage: s, onError: a, onComplete: c, signal: i } = e;
126
- try {
127
- const d = await this.initializeStreamRequest(
128
- t,
129
- n,
130
- i,
131
- r
132
- );
133
- await this.processStreamData(d, s), c?.();
134
- } catch (d) {
135
- this.handleStreamError(d, a);
136
- }
137
- }
138
- async initializeStreamRequest(t, n, e, r) {
139
- const s = _(void 0, {
140
- jwt: r
141
- }), a = await T(
142
- t,
143
- {
144
- Accept: "text/event-stream",
145
- ...s
146
- },
147
- {
148
- method: "POST",
149
- body: n,
150
- signal: e
151
- }
152
- );
153
- if (!a.ok) {
154
- const c = await a.text();
155
- let i = {};
156
- try {
157
- i = JSON.parse(c);
158
- } catch {
159
- i.error = "Failed to parse error body";
160
- }
161
- throw new O({
162
- status: a.status,
163
- message: i.error ?? "No response body"
164
- });
165
- }
166
- if (!a.body)
167
- throw new O({
168
- message: "No response body",
169
- status: a.status
170
- });
171
- return a.body.getReader();
172
- }
173
- async processStreamData(t, n) {
174
- let e = "";
175
- try {
176
- for (; ; ) {
177
- const { done: r, value: s } = await t.read();
178
- if (r) {
179
- e.trim() && this.parseSSEDataLine(e, n);
180
- break;
181
- }
182
- const a = this.decoder.decode(s, { stream: !0 });
183
- e += a;
184
- const c = e.split(`
185
- `);
186
- e = c.pop() || "";
187
- for (const i of c)
188
- this.parseSSEDataLine(i, n);
189
- }
190
- } finally {
191
- t.releaseLock();
192
- }
193
- }
194
- handleStreamError(t, n) {
195
- const e = t instanceof Error ? t : new Error(String(t));
196
- throw n?.(e), e;
197
- }
198
- parseSSEDataLine(t, n) {
199
- const e = t.trim();
200
- if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
201
- const r = e.slice(6);
202
- if (r === "[DONE]") {
203
- console.info("SSE: Stream completed");
204
- return;
205
- }
206
- let s;
207
- try {
208
- s = JSON.parse(r);
209
- } catch (a) {
210
- console.error(`Failed to parse SSE data: ${r} ${a}`);
211
- }
212
- n?.(s);
213
- }
214
- }
108
+ //#endregion
109
+ //#region libs/dial-toolkit/src/utils/rate-limits.ts
110
+ function N(e) {
111
+ if (e?.kind !== h.RATE_LIMIT || typeof e.retryAfterSeconds != "number") return null;
112
+ let t = new Date(e.occurredAt).getTime();
113
+ return Number.isNaN(t) ? null : new Date(t + e.retryAfterSeconds * 1e3);
215
114
  }
216
- const K = new k(), te = async (o, t, n, e, r) => {
217
- const { onMessage: s, onToken: a, onComplete: c, onError: i, model: d, signal: E } = n, I = {
218
- conversationId: o,
219
- messages: t,
220
- model: d,
221
- custom_fields: r
222
- };
223
- await K.streamChat(
224
- g.CHAT,
225
- I,
226
- {
227
- onMessage: (y) => L(y, s, a),
228
- onComplete: c,
229
- onError: i,
230
- signal: E
231
- },
232
- e
233
- );
234
- }, l = (o) => o instanceof Error && o.message.includes("404"), f = (o) => `/v1/conversations/${R(o)}`;
235
- function h(o) {
236
- console.warn(
237
- "[ConversationApi] suppressed error, returning empty result",
238
- o
239
- );
115
+ function P(e, t = Date.now()) {
116
+ let n = N(e);
117
+ return n ? n.getTime() > t : !1;
240
118
  }
241
- class ne {
242
- constructor(t) {
243
- this.client = t;
244
- }
245
- async getConversations(t, n, e) {
246
- const r = `${n ? e ? `${n}/${e}` : `${n}` : ""}`, s = `${u.CONVERSATIONS}/${r}`;
247
- try {
248
- return (await this.client.getRequest(s + "/?limit=1000&recursive=false", t).then((c) => c.items || [])).map((c) => {
249
- const { conversationName: i, modelId: d } = V(c);
250
- return {
251
- id: c.url?.replace("conversations/", "") || c.name,
252
- name: i,
253
- folderId: r,
254
- createdAt: c.createdAt,
255
- updatedAt: c.updatedAt,
256
- model: { id: d, name: d }
257
- };
258
- });
259
- } catch (a) {
260
- if (l(a))
261
- return h({ endpoint: s, error: a }), [];
262
- throw a;
263
- }
264
- }
265
- async getConversation(t, n) {
266
- try {
267
- return await this.client.getRequest(
268
- f(t),
269
- n
270
- );
271
- } catch (e) {
272
- if (l(e))
273
- return h({ endpoint: f(t), error: e }), null;
274
- throw e;
275
- }
276
- }
277
- async getFile(t, n) {
278
- try {
279
- const e = `${u.VERSION}/${R(t)}`;
280
- return await this.client.getRequest(e, n);
281
- } catch (e) {
282
- if (l(e))
283
- return h({ filePath: t, error: e }), null;
284
- throw e;
285
- }
286
- }
287
- async putOnboardingFile(t, n, e, r) {
288
- try {
289
- const s = `${u.VERSION}/${R(n)}`, a = "----NodeMultipartBoundary", i = [
290
- `--${a}`,
291
- `Content-Disposition: form-data; name="file"; filename="${t}"`,
292
- "Content-Type: application/json",
293
- "",
294
- JSON.stringify(e),
295
- `--${a}--`,
296
- ""
297
- ].join(`\r
298
- `);
299
- return await this.client.request(s, r, {
300
- method: "PUT",
301
- body: i,
302
- headers: C(a),
303
- isFormData: !0
304
- });
305
- } catch (s) {
306
- if (l(s))
307
- return h({ filePath: n, error: s }), null;
308
- throw s;
309
- }
310
- }
311
- async getOnboardingFile(t, n) {
312
- try {
313
- const e = `${u.VERSION}/${R(t)}`;
314
- return await this.client.getRequest(e, n);
315
- } catch (e) {
316
- if (l(e))
317
- return h({ filePath: t, error: e }), null;
318
- throw e;
319
- }
320
- }
321
- async getFileBlob(t, n) {
322
- try {
323
- const e = `${u.VERSION}/${R(t)}`;
324
- return await this.client.requestBlob(e, n, { method: "GET" });
325
- } catch (e) {
326
- if (l(e))
327
- return h({ filePath: t, error: e }), null;
328
- throw e;
329
- }
330
- }
331
- async deleteFile(t, n) {
332
- try {
333
- const e = `${u.VERSION}/${R(t)}`;
334
- await this.client.request(e, n, { method: "DELETE" });
335
- } catch (e) {
336
- if (l(e)) {
337
- h({ filePath: t, error: e });
338
- return;
339
- }
340
- throw e;
341
- }
342
- }
343
- async putFile(t, n, e) {
344
- try {
345
- const r = `${u.VERSION}/${R(t)}`, s = new FormData(), a = decodeURIComponent(t.split("/").at(-1) ?? "file");
346
- s.append("attachment", n, a), await this.client.request(r, e, {
347
- method: "PUT",
348
- body: s,
349
- isFormData: !0
350
- });
351
- } catch (r) {
352
- if (l(r)) {
353
- h({ filePath: t, error: r });
354
- return;
355
- }
356
- throw r;
357
- }
358
- }
359
- async createConversation(t, n) {
360
- const e = t?.id || P(t), { name: r, folderId: s, model: a, messages: c, custom_fields: i } = t, d = {
361
- id: e,
362
- name: r,
363
- folderId: s,
364
- model: a,
365
- messages: c || [],
366
- selectedAddons: t.selectedAddons || [],
367
- prompt: t.prompt || "",
368
- temperature: t.temperature || 0.7,
369
- createdAt: Date.now(),
370
- updatedAt: Date.now(),
371
- custom_fields: i
372
- };
373
- return await this.client.request(
374
- f(e),
375
- n,
376
- {
377
- method: "PUT",
378
- body: d
379
- }
380
- ), {
381
- id: e,
382
- name: r,
383
- folderId: s,
384
- model: a,
385
- createdAt: d.createdAt,
386
- updatedAt: d.updatedAt
387
- };
388
- }
389
- async generateConversationLink(t, n) {
390
- return await this.client.postRequest(
391
- u.SHARE_CONVERSATION,
392
- t,
393
- {
394
- body: n
395
- }
396
- );
397
- }
398
- async getSharedConversations(t, n) {
399
- return await this.client.postRequest(
400
- u.SHARE_CONVERSATION_LIST,
401
- t,
402
- {
403
- body: n
404
- }
405
- );
406
- }
407
- async revokeSharedConversations(t, n) {
408
- await this.client.postRequest(
409
- u.SHARE_CONVERSATION_REVOKE,
410
- t,
411
- {
412
- body: n
413
- }
414
- );
415
- }
416
- async updateConversation(t, n, e) {
417
- const r = await this.getConversation(t, e);
418
- if (!r)
419
- throw new Error(`Conversation with id ${t} not found`);
420
- const s = {
421
- ...r,
422
- ...n,
423
- updatedAt: Date.now()
424
- };
425
- return await this.client.request(
426
- f(t),
427
- e,
428
- {
429
- method: "PUT",
430
- body: s
431
- }
432
- );
433
- }
434
- async deleteConversation(t, n, e) {
435
- n?.isShared ? await this.client.postRequest(
436
- u.SHARE_CONVERSATION_DISCARD,
437
- e,
438
- {
439
- body: {
440
- resources: [
441
- {
442
- url: n?.url
443
- }
444
- ]
445
- }
446
- }
447
- ) : await this.client.request(f(decodeURI(t)), e, {
448
- method: "DELETE"
449
- });
450
- }
451
- async streamChat(t, n) {
452
- const e = t.model.id, r = encodeURIComponent(e), s = `${u.CHAT(r)}?api-version=${this.client.config.version}`, a = {
453
- messages: t.messages,
454
- stream: !0,
455
- temperature: 0.7,
456
- max_tokens: 4096,
457
- custom_fields: t.custom_fields
458
- };
459
- return await this.client.stream(s, n, {
460
- method: "POST",
461
- body: a,
462
- chatReference: t.conversationId
463
- });
464
- }
465
- async rateResponse(t, n, e, r) {
466
- return await this.client.postRequest(
467
- u.RATE(t),
468
- r,
469
- {
470
- body: {
471
- responseId: n,
472
- rate: e
473
- }
474
- }
475
- );
476
- }
477
- async renameConversation(t, n, e) {
478
- return await this.client.postRequest(u.RENAME, e, {
479
- body: {
480
- sourceUrl: t,
481
- destinationUrl: n,
482
- overwrite: !0
483
- }
484
- });
485
- }
119
+ function F(e, t = "en-GB") {
120
+ return {
121
+ date: e.toLocaleDateString(t),
122
+ time: e.toLocaleTimeString(t, {
123
+ hour: "2-digit",
124
+ minute: "2-digit"
125
+ })
126
+ };
486
127
  }
487
- class oe {
488
- constructor(t) {
489
- this.config = t, console.info("DialApiClient initialized", {
490
- host: t.host || "NOT SET",
491
- hasApiKey: !!t.apiKey,
492
- version: t.version
493
- });
494
- }
495
- async getRequest(t, n, e) {
496
- return this.request(t, n, { ...e, method: "GET" });
497
- }
498
- async postRequest(t, n, e) {
499
- return this.request(t, n, { ...e, method: "POST" });
500
- }
501
- async requestBlob(t, n, e) {
502
- const r = `${this.config.host}${t}`, s = {
503
- ..._(this.config.apiKey, {
504
- jwt: n,
505
- chatReference: e.chatReference,
506
- contentType: e.isFormData ? null : void 0
507
- }),
508
- ...e.headers
509
- };
510
- try {
511
- return (await T(r, s, e)).blob();
512
- } catch (a) {
513
- throw console.error("API Request Exception", {
514
- method: e.method,
515
- url: r,
516
- error: a instanceof Error ? a.message : String(a)
517
- }), a;
518
- }
519
- }
520
- async request(t, n, e) {
521
- const r = Date.now(), s = `${this.config.host}${t}`, a = {
522
- ..._(this.config.apiKey, {
523
- jwt: n,
524
- chatReference: e.chatReference,
525
- contentType: e.isFormData ? null : void 0
526
- }),
527
- ...e.headers
528
- };
529
- this.addInfoRequestLog("API Request", s, e, a);
530
- try {
531
- const c = await T(s, a, e), i = Date.now() - r;
532
- let d;
533
- const E = await c.text();
534
- try {
535
- d = E ? JSON.parse(E) : {};
536
- } catch {
537
- if (this.addErrorRequestParsing(
538
- s,
539
- e,
540
- c,
541
- i,
542
- E
543
- ), !c.ok)
544
- throw new Error(
545
- `API request failed: ${c.status} ${c.statusText} - ${E.substring(0, 100)}`
546
- );
547
- d = { data: E };
548
- }
549
- if (!c.ok) {
550
- this.addErrorRequestLog(s, e, c, i, d);
551
- const I = M(d, c);
552
- throw new Error(`API request failed: ${I}`);
553
- }
554
- return d;
555
- } catch (c) {
556
- const i = Date.now() - r;
557
- throw console.error("API Request Exception", {
558
- method: e.method,
559
- url: s,
560
- duration: `${i}ms`,
561
- error: c instanceof Error ? c.message : String(c)
562
- }), c;
563
- }
564
- }
565
- async stream(t, n, e) {
566
- const r = `${this.config.host}${t}`, s = _(
567
- this.config.apiKey,
568
- {
569
- jwt: n,
570
- chatReference: e.chatReference,
571
- contentType: e.isFormData ? null : void 0
572
- },
573
- e.headers
574
- );
575
- this.addInfoRequestLog("Stream Request", r, e, s);
576
- const a = await T(r, s, e);
577
- if (!a.ok)
578
- throw console.error("Stream Request Failed", {
579
- method: e.method || "POST",
580
- url: r,
581
- status: a.status,
582
- statusText: a.statusText
583
- }), new Error(
584
- `Stream request failed: ${a.status} ${a.statusText}`
585
- );
586
- if (!a.body)
587
- throw new Error("No response body for stream");
588
- return a.body;
589
- }
590
- addInfoRequestLog(t, n, e, r) {
591
- const s = {
592
- method: e.method || "GET",
593
- url: n,
594
- headers: $(r)
595
- };
596
- e.body && (s.body = e.body), console.info(t, s);
597
- }
598
- addErrorRequestLog(t, n, e, r, s) {
599
- console.error("API Request Failed", {
600
- method: n.method,
601
- url: t,
602
- status: e.status,
603
- statusText: e.statusText,
604
- duration: `${r}ms`,
605
- response: s
606
- });
607
- }
608
- addErrorRequestParsing(t, n, e, r, s) {
609
- console.error("API Response Parse Error", {
610
- method: n.method,
611
- url: t,
612
- status: e.status,
613
- statusText: e.statusText,
614
- duration: `${r}ms`,
615
- responseText: s.substring(0, 200),
616
- // First 200 chars
617
- error: "Response is not valid JSON"
618
- });
619
- }
128
+ //#endregion
129
+ //#region libs/dial-toolkit/src/api/chat-streaming-api.ts
130
+ var I = class {
131
+ constructor() {
132
+ this.decoder = new TextDecoder();
133
+ }
134
+ async streamChat(e, t, n = {}, r) {
135
+ let { onMessage: i, onError: a, onComplete: o, signal: s } = n;
136
+ try {
137
+ let n = await this.initializeStreamRequest(e, t, s, r);
138
+ await this.processStreamData(n, i), o?.();
139
+ } catch (e) {
140
+ this.handleStreamError(e, a);
141
+ }
142
+ }
143
+ async initializeStreamRequest(e, n, i, a) {
144
+ let o = await A(e, {
145
+ Accept: "text/event-stream",
146
+ ...r(void 0, { jwt: a })
147
+ }, {
148
+ method: "POST",
149
+ body: n,
150
+ signal: i
151
+ });
152
+ if (!o.ok) {
153
+ let e = await o.text(), n = {};
154
+ try {
155
+ n = JSON.parse(e);
156
+ } catch {
157
+ n.error = "Failed to parse error body";
158
+ }
159
+ throw new t({
160
+ status: o.status,
161
+ message: n.error ?? "No response body"
162
+ });
163
+ }
164
+ if (!o.body) throw new t({
165
+ message: "No response body",
166
+ status: o.status
167
+ });
168
+ return o.body.getReader();
169
+ }
170
+ async processStreamData(e, t) {
171
+ let n = "";
172
+ try {
173
+ for (;;) {
174
+ let { done: r, value: i } = await e.read();
175
+ if (r) {
176
+ n.trim() && this.parseSSEDataLine(n, t);
177
+ break;
178
+ }
179
+ let a = this.decoder.decode(i, { stream: !0 });
180
+ n += a;
181
+ let o = n.split("\n");
182
+ n = o.pop() || "";
183
+ for (let e of o) this.parseSSEDataLine(e, t);
184
+ }
185
+ } finally {
186
+ e.releaseLock();
187
+ }
188
+ }
189
+ handleStreamError(e, t) {
190
+ let n = e instanceof Error ? e : Error(String(e));
191
+ throw t?.(n), n;
192
+ }
193
+ parseSSEDataLine(e, t) {
194
+ let n = e.trim();
195
+ if (!(!n || n.startsWith(":")) && n.startsWith("data: ")) {
196
+ let e = n.slice(6);
197
+ if (e === "[DONE]") {
198
+ console.info("SSE: Stream completed");
199
+ return;
200
+ }
201
+ let r;
202
+ try {
203
+ r = JSON.parse(e);
204
+ } catch (t) {
205
+ console.error(`Failed to parse SSE data: ${e} ${t}`);
206
+ }
207
+ t?.(r);
208
+ }
209
+ }
210
+ }, L = new I(), R = async (t, n, r, i, a) => {
211
+ let { onMessage: o, onToken: s, onComplete: c, onError: l, model: u, signal: d } = r, f = {
212
+ conversationId: t,
213
+ messages: n,
214
+ model: u,
215
+ custom_fields: a
216
+ };
217
+ await L.streamChat(e.CHAT, f, {
218
+ onMessage: (e) => x(e, o, s),
219
+ onComplete: c,
220
+ onError: l,
221
+ signal: d
222
+ }, i);
223
+ }, z = (e) => e instanceof Error && e.message.includes("404"), B = (e) => `/v1/conversations/${j(e)}`;
224
+ function V(e) {
225
+ console.warn("[ConversationApi] suppressed error, returning empty result", e);
620
226
  }
621
- export {
622
- q as AttachmentType,
623
- G as COMPLETION_FINISH_REASON,
624
- W as CUSTOM_VIEW_STATE_KEY,
625
- k as ChatStreamSSEClient,
626
- ne as ConversationApi,
627
- u as DIAL_API_ROUTES,
628
- Y as DIAL_ERROR_CODES,
629
- B as DIAL_ERROR_TYPES,
630
- oe as DialApiClient,
631
- v as ERROR_CONTEXT_KIND,
632
- p as EXCEEDED_LIMIT,
633
- J as EXCEEDED_LIMIT_ORDER,
634
- D as InvitationType,
635
- A as ResourceTypes,
636
- w as ShareTarget,
637
- K as chatStreamSSEClient,
638
- Q as decodeApiUrl,
639
- R as encodeApiUrl,
640
- ee as formatDateTime,
641
- P as generateConversationId,
642
- M as getErrorMessage,
643
- F as getRateLimitRestoreDate,
644
- X as getSharedConversationsRequest,
645
- L as handleStreamMessage,
646
- Z as isRateLimitStillActive,
647
- z as mergeMessages,
648
- V as parseConversationName,
649
- T as sendRequest,
650
- te as streamChatResponse
227
+ var H = class {
228
+ constructor(e) {
229
+ this.client = e;
230
+ }
231
+ async getConversations(e, t, n) {
232
+ let r = `${t ? n ? `${t}/${n}` : `${t}` : ""}`, i = `${c.CONVERSATIONS}/${r}`;
233
+ try {
234
+ return (await this.client.getRequest(i + "/?limit=1000&recursive=false", e).then((e) => e.items || [])).map((e) => {
235
+ let { conversationName: t, modelId: n } = D(e);
236
+ return {
237
+ id: e.url?.replace("conversations/", "") || e.name,
238
+ name: t,
239
+ folderId: r,
240
+ createdAt: e.createdAt,
241
+ updatedAt: e.updatedAt,
242
+ model: {
243
+ id: n,
244
+ name: n
245
+ }
246
+ };
247
+ });
248
+ } catch (e) {
249
+ if (z(e)) return V({
250
+ endpoint: i,
251
+ error: e
252
+ }), [];
253
+ throw e;
254
+ }
255
+ }
256
+ async getConversation(e, t) {
257
+ try {
258
+ return await this.client.getRequest(B(e), t);
259
+ } catch (t) {
260
+ if (z(t)) return V({
261
+ endpoint: B(e),
262
+ error: t
263
+ }), null;
264
+ throw t;
265
+ }
266
+ }
267
+ async getFile(e, t) {
268
+ try {
269
+ let n = `${c.VERSION}/${j(e)}`;
270
+ return await this.client.getRequest(n, t);
271
+ } catch (t) {
272
+ if (z(t)) return V({
273
+ filePath: e,
274
+ error: t
275
+ }), null;
276
+ throw t;
277
+ }
278
+ }
279
+ async putOnboardingFile(e, t, n, r) {
280
+ try {
281
+ let a = `${c.VERSION}/${j(t)}`, o = "----NodeMultipartBoundary", s = [
282
+ `--${o}`,
283
+ `Content-Disposition: form-data; name="file"; filename="${e}"`,
284
+ "Content-Type: application/json",
285
+ "",
286
+ JSON.stringify(n),
287
+ `--${o}--`,
288
+ ""
289
+ ].join("\r\n");
290
+ return await this.client.request(a, r, {
291
+ method: "PUT",
292
+ body: s,
293
+ headers: i(o),
294
+ isFormData: !0
295
+ });
296
+ } catch (e) {
297
+ if (z(e)) return V({
298
+ filePath: t,
299
+ error: e
300
+ }), null;
301
+ throw e;
302
+ }
303
+ }
304
+ async getOnboardingFile(e, t) {
305
+ try {
306
+ let n = `${c.VERSION}/${j(e)}`;
307
+ return await this.client.getRequest(n, t);
308
+ } catch (t) {
309
+ if (z(t)) return V({
310
+ filePath: e,
311
+ error: t
312
+ }), null;
313
+ throw t;
314
+ }
315
+ }
316
+ async getFileBlob(e, t) {
317
+ try {
318
+ let n = `${c.VERSION}/${j(e)}`;
319
+ return await this.client.requestBlob(n, t, { method: "GET" });
320
+ } catch (t) {
321
+ if (z(t)) return V({
322
+ filePath: e,
323
+ error: t
324
+ }), null;
325
+ throw t;
326
+ }
327
+ }
328
+ async deleteFile(e, t) {
329
+ try {
330
+ let n = `${c.VERSION}/${j(e)}`;
331
+ await this.client.request(n, t, { method: "DELETE" });
332
+ } catch (t) {
333
+ if (z(t)) {
334
+ V({
335
+ filePath: e,
336
+ error: t
337
+ });
338
+ return;
339
+ }
340
+ throw t;
341
+ }
342
+ }
343
+ async putFile(e, t, n) {
344
+ try {
345
+ let r = `${c.VERSION}/${j(e)}`, i = new FormData(), a = decodeURIComponent(e.split("/").at(-1) ?? "file");
346
+ i.append("attachment", t, a), await this.client.request(r, n, {
347
+ method: "PUT",
348
+ body: i,
349
+ isFormData: !0
350
+ });
351
+ } catch (t) {
352
+ if (z(t)) {
353
+ V({
354
+ filePath: e,
355
+ error: t
356
+ });
357
+ return;
358
+ }
359
+ throw t;
360
+ }
361
+ }
362
+ async createConversation(e, t) {
363
+ let n = e?.id || O(e), { name: r, folderId: i, model: a, messages: o, custom_fields: s } = e, c = {
364
+ id: n,
365
+ name: r,
366
+ folderId: i,
367
+ model: a,
368
+ messages: o || [],
369
+ selectedAddons: e.selectedAddons || [],
370
+ prompt: e.prompt || "",
371
+ temperature: e.temperature || .7,
372
+ createdAt: Date.now(),
373
+ updatedAt: Date.now(),
374
+ custom_fields: s
375
+ };
376
+ return await this.client.request(B(n), t, {
377
+ method: "PUT",
378
+ body: c
379
+ }), {
380
+ id: n,
381
+ name: r,
382
+ folderId: i,
383
+ model: a,
384
+ createdAt: c.createdAt,
385
+ updatedAt: c.updatedAt
386
+ };
387
+ }
388
+ async generateConversationLink(e, t) {
389
+ return await this.client.postRequest(c.SHARE_CONVERSATION, e, { body: t });
390
+ }
391
+ async getSharedConversations(e, t) {
392
+ return await this.client.postRequest(c.SHARE_CONVERSATION_LIST, e, { body: t });
393
+ }
394
+ async revokeSharedConversations(e, t) {
395
+ await this.client.postRequest(c.SHARE_CONVERSATION_REVOKE, e, { body: t });
396
+ }
397
+ async updateConversation(e, t, n) {
398
+ let r = await this.getConversation(e, n);
399
+ if (!r) throw Error(`Conversation with id ${e} not found`);
400
+ let i = {
401
+ ...r,
402
+ ...t,
403
+ updatedAt: Date.now()
404
+ };
405
+ return await this.client.request(B(e), n, {
406
+ method: "PUT",
407
+ body: i
408
+ });
409
+ }
410
+ async deleteConversation(e, t, n) {
411
+ t?.isShared ? await this.client.postRequest(c.SHARE_CONVERSATION_DISCARD, n, { body: { resources: [{ url: t?.url }] } }) : await this.client.request(B(decodeURI(e)), n, { method: "DELETE" });
412
+ }
413
+ async streamChat(e, t) {
414
+ let n = e.model.id, r = encodeURIComponent(n), i = `${c.CHAT(r)}?api-version=${this.client.config.version}`, a = {
415
+ messages: e.messages,
416
+ stream: !0,
417
+ temperature: .7,
418
+ max_tokens: 4096,
419
+ custom_fields: e.custom_fields
420
+ };
421
+ return await this.client.stream(i, t, {
422
+ method: "POST",
423
+ body: a,
424
+ chatReference: e.conversationId
425
+ });
426
+ }
427
+ async rateResponse(e, t, n, r) {
428
+ return await this.client.postRequest(c.RATE(e), r, { body: {
429
+ responseId: t,
430
+ rate: n
431
+ } });
432
+ }
433
+ async renameConversation(e, t, n) {
434
+ return await this.client.postRequest(c.RENAME, n, { body: {
435
+ sourceUrl: e,
436
+ destinationUrl: t,
437
+ overwrite: !0
438
+ } });
439
+ }
440
+ }, U = class {
441
+ constructor(e) {
442
+ this.config = e, console.info("DialApiClient initialized", {
443
+ host: e.host || "NOT SET",
444
+ hasApiKey: !!e.apiKey,
445
+ version: e.version
446
+ });
447
+ }
448
+ async getRequest(e, t, n) {
449
+ return this.request(e, t, {
450
+ ...n,
451
+ method: "GET"
452
+ });
453
+ }
454
+ async postRequest(e, t, n) {
455
+ return this.request(e, t, {
456
+ ...n,
457
+ method: "POST"
458
+ });
459
+ }
460
+ async requestBlob(e, t, n) {
461
+ let i = `${this.config.host}${e}`, a = {
462
+ ...r(this.config.apiKey, {
463
+ jwt: t,
464
+ chatReference: n.chatReference,
465
+ contentType: n.isFormData ? null : void 0
466
+ }),
467
+ ...n.headers
468
+ };
469
+ try {
470
+ return (await A(i, a, n)).blob();
471
+ } catch (e) {
472
+ throw console.error("API Request Exception", {
473
+ method: n.method,
474
+ url: i,
475
+ error: e instanceof Error ? e.message : String(e)
476
+ }), e;
477
+ }
478
+ }
479
+ async request(e, t, n) {
480
+ let i = Date.now(), a = `${this.config.host}${e}`, o = {
481
+ ...r(this.config.apiKey, {
482
+ jwt: t,
483
+ chatReference: n.chatReference,
484
+ contentType: n.isFormData ? null : void 0
485
+ }),
486
+ ...n.headers
487
+ };
488
+ this.addInfoRequestLog("API Request", a, n, o);
489
+ try {
490
+ let e = await A(a, o, n), t = Date.now() - i, r, s = await e.text();
491
+ try {
492
+ r = s ? JSON.parse(s) : {};
493
+ } catch {
494
+ if (this.addErrorRequestParsing(a, n, e, t, s), !e.ok) throw Error(`API request failed: ${e.status} ${e.statusText} - ${s.substring(0, 100)}`);
495
+ r = { data: s };
496
+ }
497
+ if (!e.ok) {
498
+ this.addErrorRequestLog(a, n, e, t, r);
499
+ let i = S(r, e);
500
+ throw Error(`API request failed: ${i}`);
501
+ }
502
+ return r;
503
+ } catch (e) {
504
+ let t = Date.now() - i;
505
+ throw console.error("API Request Exception", {
506
+ method: n.method,
507
+ url: a,
508
+ duration: `${t}ms`,
509
+ error: e instanceof Error ? e.message : String(e)
510
+ }), e;
511
+ }
512
+ }
513
+ async stream(e, t, n) {
514
+ let i = `${this.config.host}${e}`, a = r(this.config.apiKey, {
515
+ jwt: t,
516
+ chatReference: n.chatReference,
517
+ contentType: n.isFormData ? null : void 0
518
+ }, n.headers);
519
+ this.addInfoRequestLog("Stream Request", i, n, a);
520
+ let o = await A(i, a, n);
521
+ if (!o.ok) throw console.error("Stream Request Failed", {
522
+ method: n.method || "POST",
523
+ url: i,
524
+ status: o.status,
525
+ statusText: o.statusText
526
+ }), Error(`Stream request failed: ${o.status} ${o.statusText}`);
527
+ if (!o.body) throw Error("No response body for stream");
528
+ return o.body;
529
+ }
530
+ addInfoRequestLog(e, t, n, r) {
531
+ let i = {
532
+ method: n.method || "GET",
533
+ url: t,
534
+ headers: a(r)
535
+ };
536
+ n.body && (i.body = n.body), console.info(e, i);
537
+ }
538
+ addErrorRequestLog(e, t, n, r, i) {
539
+ console.error("API Request Failed", {
540
+ method: t.method,
541
+ url: e,
542
+ status: n.status,
543
+ statusText: n.statusText,
544
+ duration: `${r}ms`,
545
+ response: i
546
+ });
547
+ }
548
+ addErrorRequestParsing(e, t, n, r, i) {
549
+ console.error("API Response Parse Error", {
550
+ method: t.method,
551
+ url: e,
552
+ status: n.status,
553
+ statusText: n.statusText,
554
+ duration: `${r}ms`,
555
+ responseText: i.substring(0, 200),
556
+ error: "Response is not valid JSON"
557
+ });
558
+ }
651
559
  };
560
+ //#endregion
561
+ export { v as AttachmentType, l as COMPLETION_FINISH_REASON, m as CUSTOM_VIEW_STATE_KEY, I as ChatStreamSSEClient, H as ConversationApi, c as DIAL_API_ROUTES, d as DIAL_ERROR_CODES, f as DIAL_ERROR_TYPES, U as DialApiClient, h as ERROR_CONTEXT_KIND, u as EXCEEDED_LIMIT, p as EXCEEDED_LIMIT_ORDER, y as InvitationType, g as ResourceTypes, _ as ShareTarget, L as chatStreamSSEClient, M as decodeApiUrl, j as encodeApiUrl, F as formatDateTime, O as generateConversationId, S as getErrorMessage, N as getRateLimitRestoreDate, k as getSharedConversationsRequest, x as handleStreamMessage, P as isRateLimitStillActive, w as mergeMessages, D as parseConversationName, A as sendRequest, R as streamChatResponse };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.7.0-dev.20",
3
+ "version": "0.7.0-dev.21",
4
4
  "license": "MIT",
5
5
  "exports": {
6
6
  ".": {
@@ -14,7 +14,7 @@
14
14
  "module": "./index.mjs",
15
15
  "types": "./index.d.ts",
16
16
  "dependencies": {
17
- "@epam/statgpt-shared-toolkit": "0.7.0-dev.20"
17
+ "@epam/statgpt-shared-toolkit": "0.7.0-dev.21"
18
18
  },
19
19
  "peerDependencies": {
20
20
  "@epam/ai-dial-shared": "^0.43.3"
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 EPAM Systems
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.