@epam/statgpt-dial-toolkit 0.5.0-rc.9 → 0.5.0

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