@epam/statgpt-dial-toolkit 0.4.0-rc.3 → 0.4.0-rc.30

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