@epam/statgpt-dial-toolkit 0.2.0-rc.35 → 0.2.0-rc.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.cjs +3 -3
  2. package/index.mjs +157 -141
  3. package/package.json +2 -2
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m="v1",R=`/${m}/ops/resource/share`,u={VERSION:`/${m}`,BUCKET:`/${m}/bucket`,CONVERSATIONS:`/${m}/metadata/conversations`,CONVERSATION_BY_ID:n=>`/${m}/metadata/conversations/${n}`,CHAT:n=>`/openai/deployments/${n}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:n=>`/${m}/deployments/${n}/configuration`,SHARE_CONVERSATION:`${R}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${m}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${m}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:n=>`/${m}/${n}/rate`,RENAME:`/${m}/ops/resource/move`};var O=(n=>(n.CONVERSATION="CONVERSATION",n))(O||{}),I=(n=>(n.ME="me",n.OTHERS="others",n))(I||{}),p=(n=>(n.CSV="text/csv",n.TABLE="application/dial-ttyd-table",n.PLOTLY="application/vnd.plotly.v1+json",n.MARKDOWN="text/markdown",n.JSON="application/json",n.JPEG="image/jpeg",n.PNG="image/png",n.CUSTOM_DATA_GRID="custom_data_grid",n.CUSTOM_CHART="custom_chart",n))(p||{}),T=(n=>(n.LINK="link",n))(T||{});const P=n=>{var t,r,e,s,o,a;return n.content?(console.info(`Using direct content format: ${n.content}`),n.content):(e=(r=(t=n.choices)==null?void 0:t[0])==null?void 0:r.delta)!=null&&e.content?(console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`),n.choices[0].delta.content):(a=(o=(s=n.choices)==null?void 0:s[0])==null?void 0:o.message)!=null&&a.content?(console.info(`Using complete message format: ${n.choices[0].message.content}`),n.choices[0].message.content):(console.info("Unknown SSE data format:",n),null)},g=(n,t,r)=>{if(t==null||t(n),r){const e=P(n);e&&r(e)}},$=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,x=(n,t)=>{const r=n==null?void 0:n.reduce((e,s)=>(e[s.index]=s,e),{});return t.forEach(e=>{r[e.index]?(e.attachments&&(r[e.index].attachments=(r[e.index].attachments||[]).concat(e.attachments)),e.content&&(r[e.index].content=(r[e.index].content||"")+e.content),e.name&&(r[e.index].name=(r[e.index].name||"")+e.name),e.status&&(r[e.index].status=e.status)):r[e.index]=e}),Object.values(r)},D=(n,t)=>{const r=structuredClone(n);return t.forEach(e=>{e.errorMessage&&(r.errorMessage=e.errorMessage),e.role&&(r.role=e.role),e.responseId&&(r.responseId=e.responseId),e.content&&H(r,e),e.custom_content&&(r.custom_content||(r.custom_content={}),e.custom_content.attachments&&(r.custom_content.attachments||(r.custom_content.attachments=[]),r.custom_content.attachments=r.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(r.custom_content.stages||(r.custom_content.stages=[]),r.custom_content.stages=x(r.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(r.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(r.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(r.custom_content.form_value=e.custom_content.form_value))}),r};function H(n,t){if(t.content){const r=V(t.content);r!=null?n.content=n.content.slice(0,-r):n.content=`${n.content||""}${t.content}`}}function V(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const L={CHAT:"/api/chat"},U="application/json",j="Content-Type",A="Api-Key",M="X-CONVERSATION-ID",y="Ocp-Apim-Subscription-Key",k=n=>(n==null?void 0:n.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," "))||"",C=(n,t,r)=>{const e={[j]:(t==null?void 0:t.contentType)||U};return t!=null&&t.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[A]=n),t!=null&&t.chatReference&&(e[M]=t.chatReference),{...e,...r}},K=n=>{const t={...n};return t[A]&&(t[A]=t[A].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[y]&&(t[y]=t[y].substring(0,8)+"...[REDACTED]"),t},B=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),N=n=>{var s;const t=((s=n.name)==null?void 0:s.split("__"))||[],r=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:r}},w=n=>{const t=Date.now(),r=k(n.name);return`${n.folderId}/${r}-${t}`},F=n=>({resourceTypes:[O.CONVERSATION],with:n}),E=async(n,t,r)=>await fetch(n,{method:r.method||"GET",headers:t,body:r!=null&&r.isFormData&&typeof(r==null?void 0:r.body)=="string"?r.body:JSON.stringify(r.body),signal:r==null?void 0:r.signal});function f(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function J(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,r,e={},s){const{onMessage:o,onError:a,onComplete:c,signal:d}=e;try{const i=await this.initializeStreamRequest(t,r,d,s);await this.processStreamData(i,o),c==null||c()}catch(i){this.handleStreamError(i,a)}}async initializeStreamRequest(t,r,e,s){const o=C(void 0,{jwt:s}),a=await E(t,{Accept:"text/event-stream",...o},{method:"POST",body:r,signal:e});if(!a.ok){const c=await a.text();throw new Error(JSON.stringify({status:a.status,message:c}))}if(!a.body)throw new Error("No response body");return a.body.getReader()}async processStreamData(t,r){let e="";try{for(;;){const{done:s,value:o}=await t.read();if(s){e.trim()&&this.parseSSEDataLine(e,r);break}const a=this.decoder.decode(o,{stream:!0});e+=a;const c=e.split(`
2
- `);e=c.pop()||"";for(const d of c)this.parseSSEDataLine(d,r)}}finally{t.releaseLock()}}handleStreamError(t,r){const e=t instanceof Error?t:new Error(String(t));throw r==null||r(e),e}parseSSEDataLine(t,r){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const s=e.slice(6);if(s==="[DONE]"){console.info("SSE: Stream completed");return}try{const o=JSON.parse(s);r==null||r(o)}catch(o){console.error(`Failed to parse SSE data: ${s} ${o}`)}}}}const v=new q,z=async(n,t,r,e,s)=>{const{onMessage:o,onToken:a,onComplete:c,onError:d,model:i,signal:l}=r,_={conversationId:n,messages:t,model:i,custom_fields:s};await v.streamChat(L.CHAT,_,{onMessage:b=>g(b,o,a),onComplete:c,onError:d,signal:l},e)},h=n=>n instanceof Error&&n.message.includes("404"),S=n=>`/v1/conversations/${f(n)}`;class G{constructor(t){this.client=t}async getConversations(t,r,e){const s=`${r?e?`${r}/${e}`:`${r}`:""}`,o=`${u.CONVERSATIONS}/${s}`;try{return(await this.client.getRequest(o+"/?limit=1000&recursive=false",t).then(c=>c.items||[])).map(c=>{var l;const{conversationName:d,modelId:i}=N(c);return{id:((l=c.url)==null?void 0:l.replace("conversations/",""))||c.name,name:d,folderId:s,createdAt:c.createdAt,updatedAt:c.updatedAt,model:{id:i,name:i}}})}catch(a){if(h(a))return[];throw a}}async getConversation(t,r){try{return await this.client.getRequest(S(t),r)}catch(e){if(h(e))return null;throw e}}async getFile(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.getRequest(e,r)}catch(e){if(h(e))return null;throw e}}async putOnboardingFile(t,r,e,s){try{const o=`${u.VERSION}/${f(r)}`,a="----NodeMultipartBoundary",d=[`--${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,s,{method:"PUT",body:d,headers:B(a),isFormData:!0})}catch(o){if(h(o))return null;throw o}}async getOnboardingFile(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.getRequest(e,r)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.requestBlob(e,r,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,r){const e=(t==null?void 0:t.id)||w(t),{name:s,folderId:o,model:a,messages:c,custom_fields:d}=t,i={id:e,name:s,folderId:o,model:a,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:d};return await this.client.request(S(e),r,{method:"PUT",body:i}),{id:e,name:s,folderId:o,model:a,createdAt:i.createdAt,updatedAt:i.updatedAt}}async generateConversationLink(t,r){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:r})}async getSharedConversations(t,r){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:r})}async revokeSharedConversations(t,r){await this.client.postRequest(u.SHARE_CONVERSATION_REVOKE,t,{body:r})}async updateConversation(t,r,e){const s=await this.getConversation(t,e);if(!s)throw new Error(`Conversation with id ${t} not found`);const o={...s,...r,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:o})}async deleteConversation(t,r,e){r!=null&&r.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:r==null?void 0:r.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,r){const e=t.model.id,s=encodeURIComponent(e),o=`${u.CHAT(s)}?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,r,{method:"POST",body:a,chatReference:t.conversationId})}async rateResponse(t,r,e,s){return await this.client.postRequest(u.RATE(t),s,{body:{responseId:r,rate:e}})}async renameConversation(t,r,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:r,overwrite:!0}})}}class Y{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,r,e){return this.request(t,r,{...e,method:"GET"})}async postRequest(t,r,e){return this.request(t,r,{...e,method:"POST"})}async requestBlob(t,r,e){const s=`${this.config.host}${t}`,o={...C(this.config.apiKey,{jwt:r,chatReference:e.chatReference}),...e.headers};try{return(await E(s,o,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:s,error:a instanceof Error?a.message:String(a)}),a}}async request(t,r,e){const s=Date.now(),o=`${this.config.host}${t}`,a={...C(this.config.apiKey,{jwt:r,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",o,e,a);try{const c=await E(o,a,e),d=Date.now()-s;let i;const l=await c.text();try{i=l?JSON.parse(l):{}}catch{if(this.addErrorRequestParsing(o,e,c,d,l),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${l.substring(0,100)}`);i={data:l}}if(!c.ok){this.addErrorRequestLog(o,e,c,d,i);const _=$(i,c);throw new Error(`API request failed: ${_}`)}return i}catch(c){const d=Date.now()-s;throw console.error("API Request Exception",{method:e.method,url:o,duration:`${d}ms`,error:c instanceof Error?c.message:String(c)}),c}}async stream(t,r,e){const s=`${this.config.host}${t}`,o=C(this.config.apiKey,{jwt:r,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",s,e,o);const a=await E(s,o,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:s,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,r,e,s){const o={method:e.method||"GET",url:r,headers:K(s)};e.body&&(o.body=e.body),console.info(t,o)}addErrorRequestLog(t,r,e,s,o){console.error("API Request Failed",{method:r.method,url:t,status:e.status,statusText:e.statusText,duration:`${s}ms`,response:o})}addErrorRequestParsing(t,r,e,s,o){console.error("API Response Parse Error",{method:r.method,url:t,status:e.status,statusText:e.statusText,duration:`${s}ms`,responseText:o.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=p;exports.ChatStreamSSEClient=q;exports.ConversationApi=G;exports.DIAL_API_ROUTES=u;exports.DialApiClient=Y;exports.InvitationType=T;exports.ResourceTypes=O;exports.ShareTarget=I;exports.chatStreamSSEClient=v;exports.decodeApiUrl=J;exports.encodeApiUrl=f;exports.generateConversationId=w;exports.getErrorMessage=$;exports.getSharedConversationsRequest=F;exports.handleStreamMessage=g;exports.mergeMessages=D;exports.parseConversationName=N;exports.sendRequest=E;exports.streamChatResponse=z;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m="v1",R=`/${m}/ops/resource/share`,u={VERSION:`/${m}`,BUCKET:`/${m}/bucket`,CONVERSATIONS:`/${m}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${m}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${m}/deployments/${s}/configuration`,SHARE_CONVERSATION:`${R}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${m}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${m}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:s=>`/${m}/${s}/rate`,RENAME:`/${m}/ops/resource/move`};var y=(s=>(s.CONVERSATION="CONVERSATION",s))(y||{}),I=(s=>(s.ME="me",s.OTHERS="others",s))(I||{}),g=(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.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s))(g||{}),T=(s=>(s.LINK="link",s))(T||{});const x=s=>{var t,r,e,n,o,a;return s.content?(console.info(`Using direct content format: ${s.content}`),s.content):(e=(r=(t=s.choices)==null?void 0:t[0])==null?void 0:r.delta)!=null&&e.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):(a=(o=(n=s.choices)==null?void 0:n[0])==null?void 0:o.message)!=null&&a.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)},N=(s,t,r)=>{if(t==null||t(s),r){const e=x(s);e&&r(e)}},$=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,H=(s,t)=>{const r=s==null?void 0:s.reduce((e,n)=>(e[n.index]=n,e),{});return t.forEach(e=>{r[e.index]?(e.attachments&&(r[e.index].attachments=(r[e.index].attachments||[]).concat(e.attachments)),e.content&&(r[e.index].content=(r[e.index].content||"")+e.content),e.name&&(r[e.index].name=(r[e.index].name||"")+e.name),e.status&&(r[e.index].status=e.status)):r[e.index]=e}),Object.values(r)},D=(s,t)=>{const r=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(r.errorMessage=e.errorMessage),e.role&&(r.role=e.role),e.responseId&&(r.responseId=e.responseId),e.content&&V(r,e),e.custom_content&&(r.custom_content||(r.custom_content={}),e.custom_content.attachments&&(r.custom_content.attachments||(r.custom_content.attachments=[]),r.custom_content.attachments=r.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(r.custom_content.stages||(r.custom_content.stages=[]),r.custom_content.stages=H(r.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(r.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(r.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(r.custom_content.form_value=e.custom_content.form_value))}),r};function V(s,t){if(t.content){const r=L(t.content);r!=null?s.content=s.content.slice(0,-r):s.content=`${s.content||""}${t.content}`}}function L(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const U={CHAT:"/api/chat"},j="application/json",M="Content-Type",A="Api-Key",k="X-CONVERSATION-ID",_="Ocp-Apim-Subscription-Key";class O extends Error{constructor(t){super(t.message),this.name="HttpError",this.status=t.status,this.details=t.details}}const K=s=>(s==null?void 0:s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," "))||"",C=(s,t,r)=>{const e={[M]:(t==null?void 0:t.contentType)||j};return t!=null&&t.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[A]=s),t!=null&&t.chatReference&&(e[k]=t.chatReference),{...e,...r}},F=s=>{const t={...s};return t[A]&&(t[A]=t[A].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[_]&&(t[_]=t[_].substring(0,8)+"...[REDACTED]"),t},B=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),w=s=>{var n;const t=((n=s.name)==null?void 0:n.split("__"))||[],r=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:r}},b=s=>{const t=Date.now(),r=K(s.name);return`${s.folderId}/${r}-${t}`},J=s=>({resourceTypes:[y.CONVERSATION],with:s}),E=async(s,t,r)=>await fetch(s,{method:r.method||"GET",headers:t,body:r!=null&&r.isFormData&&typeof(r==null?void 0:r.body)=="string"?r.body:JSON.stringify(r.body),signal:r==null?void 0:r.signal});function f(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function z(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,r,e={},n){const{onMessage:o,onError:a,onComplete:c,signal:i}=e;try{const d=await this.initializeStreamRequest(t,r,i,n);await this.processStreamData(d,o),c==null||c()}catch(d){this.handleStreamError(d,a)}}async initializeStreamRequest(t,r,e,n){const o=C(void 0,{jwt:n}),a=await E(t,{Accept:"text/event-stream",...o},{method:"POST",body:r,signal:e});if(!a.ok){const c=await a.text();let i={};try{i=JSON.parse(c)}catch{i.message="Failed to parse error body"}throw new O({status:a.status,message:i.message??"No response body"})}if(!a.body)throw new O({message:"No response body",status:a.status});return a.body.getReader()}async processStreamData(t,r){let e="";try{for(;;){const{done:n,value:o}=await t.read();if(n){e.trim()&&this.parseSSEDataLine(e,r);break}const a=this.decoder.decode(o,{stream:!0});e+=a;const c=e.split(`
2
+ `);e=c.pop()||"";for(const i of c)this.parseSSEDataLine(i,r)}}finally{t.releaseLock()}}handleStreamError(t,r){const e=t instanceof Error?t:new Error(String(t));throw r==null||r(e),e}parseSSEDataLine(t,r){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const n=e.slice(6);if(n==="[DONE]"){console.info("SSE: Stream completed");return}try{const o=JSON.parse(n);r==null||r(o)}catch(o){console.error(`Failed to parse SSE data: ${n} ${o}`)}}}}const v=new q,G=async(s,t,r,e,n)=>{const{onMessage:o,onToken:a,onComplete:c,onError:i,model:d,signal:l}=r,p={conversationId:s,messages:t,model:d,custom_fields:n};await v.streamChat(U.CHAT,p,{onMessage:P=>N(P,o,a),onComplete:c,onError:i,signal:l},e)},h=s=>s instanceof Error&&s.message.includes("404"),S=s=>`/v1/conversations/${f(s)}`;class Y{constructor(t){this.client=t}async getConversations(t,r,e){const n=`${r?e?`${r}/${e}`:`${r}`:""}`,o=`${u.CONVERSATIONS}/${n}`;try{return(await this.client.getRequest(o+"/?limit=1000&recursive=false",t).then(c=>c.items||[])).map(c=>{var l;const{conversationName:i,modelId:d}=w(c);return{id:((l=c.url)==null?void 0:l.replace("conversations/",""))||c.name,name:i,folderId:n,createdAt:c.createdAt,updatedAt:c.updatedAt,model:{id:d,name:d}}})}catch(a){if(h(a))return[];throw a}}async getConversation(t,r){try{return await this.client.getRequest(S(t),r)}catch(e){if(h(e))return null;throw e}}async getFile(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.getRequest(e,r)}catch(e){if(h(e))return null;throw e}}async putOnboardingFile(t,r,e,n){try{const o=`${u.VERSION}/${f(r)}`,a="----NodeMultipartBoundary",i=[`--${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,n,{method:"PUT",body:i,headers:B(a),isFormData:!0})}catch(o){if(h(o))return null;throw o}}async getOnboardingFile(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.getRequest(e,r)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,r){try{const e=`${u.VERSION}/${f(t)}`;return await this.client.requestBlob(e,r,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,r){const e=(t==null?void 0:t.id)||b(t),{name:n,folderId:o,model:a,messages:c,custom_fields:i}=t,d={id:e,name:n,folderId:o,model:a,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:i};return await this.client.request(S(e),r,{method:"PUT",body:d}),{id:e,name:n,folderId:o,model:a,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,r){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:r})}async getSharedConversations(t,r){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:r})}async revokeSharedConversations(t,r){await this.client.postRequest(u.SHARE_CONVERSATION_REVOKE,t,{body:r})}async updateConversation(t,r,e){const n=await this.getConversation(t,e);if(!n)throw new Error(`Conversation with id ${t} not found`);const o={...n,...r,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:o})}async deleteConversation(t,r,e){r!=null&&r.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:r==null?void 0:r.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,r){const e=t.model.id,n=encodeURIComponent(e),o=`${u.CHAT(n)}?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,r,{method:"POST",body:a,chatReference:t.conversationId})}async rateResponse(t,r,e,n){return await this.client.postRequest(u.RATE(t),n,{body:{responseId:r,rate:e}})}async renameConversation(t,r,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:r,overwrite:!0}})}}class W{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,r,e){return this.request(t,r,{...e,method:"GET"})}async postRequest(t,r,e){return this.request(t,r,{...e,method:"POST"})}async requestBlob(t,r,e){const n=`${this.config.host}${t}`,o={...C(this.config.apiKey,{jwt:r,chatReference:e.chatReference}),...e.headers};try{return(await E(n,o,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:n,error:a instanceof Error?a.message:String(a)}),a}}async request(t,r,e){const n=Date.now(),o=`${this.config.host}${t}`,a={...C(this.config.apiKey,{jwt:r,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",o,e,a);try{const c=await E(o,a,e),i=Date.now()-n;let d;const l=await c.text();try{d=l?JSON.parse(l):{}}catch{if(this.addErrorRequestParsing(o,e,c,i,l),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${l.substring(0,100)}`);d={data:l}}if(!c.ok){this.addErrorRequestLog(o,e,c,i,d);const p=$(d,c);throw new Error(`API request failed: ${p}`)}return d}catch(c){const i=Date.now()-n;throw console.error("API Request Exception",{method:e.method,url:o,duration:`${i}ms`,error:c instanceof Error?c.message:String(c)}),c}}async stream(t,r,e){const n=`${this.config.host}${t}`,o=C(this.config.apiKey,{jwt:r,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",n,e,o);const a=await E(n,o,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:n,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,r,e,n){const o={method:e.method||"GET",url:r,headers:F(n)};e.body&&(o.body=e.body),console.info(t,o)}addErrorRequestLog(t,r,e,n,o){console.error("API Request Failed",{method:r.method,url:t,status:e.status,statusText:e.statusText,duration:`${n}ms`,response:o})}addErrorRequestParsing(t,r,e,n,o){console.error("API Response Parse Error",{method:r.method,url:t,status:e.status,statusText:e.statusText,duration:`${n}ms`,responseText:o.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=g;exports.ChatStreamSSEClient=q;exports.ConversationApi=Y;exports.DIAL_API_ROUTES=u;exports.DialApiClient=W;exports.InvitationType=T;exports.ResourceTypes=y;exports.ShareTarget=I;exports.chatStreamSSEClient=v;exports.decodeApiUrl=z;exports.encodeApiUrl=f;exports.generateConversationId=b;exports.getErrorMessage=$;exports.getSharedConversationsRequest=J;exports.handleStreamMessage=N;exports.mergeMessages=D;exports.parseConversationName=w;exports.sendRequest=E;exports.streamChatResponse=G;
package/index.mjs CHANGED
@@ -2,111 +2,117 @@ const E = "/v1/ops/resource/share", u = {
2
2
  VERSION: "/v1",
3
3
  BUCKET: "/v1/bucket",
4
4
  CONVERSATIONS: "/v1/metadata/conversations",
5
- CONVERSATION_BY_ID: (n) => `/v1/metadata/conversations/${n}`,
6
- CHAT: (n) => `/openai/deployments/${n}/chat/completions`,
5
+ CONVERSATION_BY_ID: (s) => `/v1/metadata/conversations/${s}`,
6
+ CHAT: (s) => `/openai/deployments/${s}/chat/completions`,
7
7
  MODELS: "/openai/models",
8
- CONFIGURATION: (n) => `/v1/deployments/${n}/configuration`,
8
+ CONFIGURATION: (s) => `/v1/deployments/${s}/configuration`,
9
9
  SHARE_CONVERSATION: `${E}/create`,
10
- SHARE_CONVERSATION_ACCEPT: (n) => `/v1/invitations/${n}?accept=true`,
11
- SHARE_CONVERSATION_DETAILS: (n) => `/v1/invitations/${n}`,
10
+ SHARE_CONVERSATION_ACCEPT: (s) => `/v1/invitations/${s}?accept=true`,
11
+ SHARE_CONVERSATION_DETAILS: (s) => `/v1/invitations/${s}`,
12
12
  SHARE_CONVERSATION_LIST: `${E}/list`,
13
13
  SHARE_CONVERSATION_DISCARD: `${E}/discard`,
14
14
  SHARE_CONVERSATION_REVOKE: `${E}/revoke`,
15
- RATE: (n) => `/v1/${n}/rate`,
15
+ RATE: (s) => `/v1/${s}/rate`,
16
16
  RENAME: "/v1/ops/resource/move"
17
17
  };
18
- var _ = /* @__PURE__ */ ((n) => (n.CONVERSATION = "CONVERSATION", n))(_ || {}), N = /* @__PURE__ */ ((n) => (n.ME = "me", n.OTHERS = "others", n))(N || {}), y = /* @__PURE__ */ ((n) => (n.CSV = "text/csv", n.TABLE = "application/dial-ttyd-table", n.PLOTLY = "application/vnd.plotly.v1+json", n.MARKDOWN = "text/markdown", n.JSON = "application/json", n.JPEG = "image/jpeg", n.PNG = "image/png", n.CUSTOM_DATA_GRID = "custom_data_grid", n.CUSTOM_CHART = "custom_chart", n))(y || {}), T = /* @__PURE__ */ ((n) => (n.LINK = "link", n))(T || {});
19
- const $ = (n) => {
20
- var t, r, e, s, o, c;
21
- return n.content ? (console.info(`Using direct content format: ${n.content}`), n.content) : (e = (r = (t = n.choices) == null ? void 0 : t[0]) == null ? void 0 : r.delta) != null && e.content ? (console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`), n.choices[0].delta.content) : (c = (o = (s = n.choices) == null ? void 0 : s[0]) == null ? void 0 : o.message) != null && c.content ? (console.info(
22
- `Using complete message format: ${n.choices[0].message.content}`
23
- ), n.choices[0].message.content) : (console.info("Unknown SSE data format:", n), null);
24
- }, p = (n, t, r) => {
25
- if (t == null || t(n), r) {
26
- const e = $(n);
18
+ var C = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(C || {}), y = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(y || {}), p = /* @__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.CUSTOM_DATA_GRID = "custom_data_grid", s.CUSTOM_CHART = "custom_chart", s))(p || {}), T = /* @__PURE__ */ ((s) => (s.LINK = "link", s))(T || {});
19
+ const $ = (s) => {
20
+ var t, r, e, n, o, c;
21
+ return s.content ? (console.info(`Using direct content format: ${s.content}`), s.content) : (e = (r = (t = s.choices) == null ? void 0 : t[0]) == null ? void 0 : r.delta) != null && e.content ? (console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`), s.choices[0].delta.content) : (c = (o = (n = s.choices) == null ? void 0 : n[0]) == null ? void 0 : o.message) != null && c.content ? (console.info(
22
+ `Using complete message format: ${s.choices[0].message.content}`
23
+ ), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null);
24
+ }, g = (s, t, r) => {
25
+ if (t == null || t(s), r) {
26
+ const e = $(s);
27
27
  e && r(e);
28
28
  }
29
- }, g = (n, t) => n.error || n.message || `${t.status} ${t.statusText}`, w = (n, t) => {
30
- const r = n == null ? void 0 : n.reduce(
31
- (e, s) => (e[s.index] = s, e),
29
+ }, w = (s, t) => s.error || s.message || `${t.status} ${t.statusText}`, b = (s, t) => {
30
+ const r = s == null ? void 0 : s.reduce(
31
+ (e, n) => (e[n.index] = n, e),
32
32
  {}
33
33
  );
34
34
  return t.forEach((e) => {
35
35
  r[e.index] ? (e.attachments && (r[e.index].attachments = (r[e.index].attachments || []).concat(e.attachments)), e.content && (r[e.index].content = (r[e.index].content || "") + e.content), e.name && (r[e.index].name = (r[e.index].name || "") + e.name), e.status && (r[e.index].status = e.status)) : r[e.index] = e;
36
36
  }), Object.values(r);
37
- }, B = (n, t) => {
38
- const r = structuredClone(n);
37
+ }, B = (s, t) => {
38
+ const r = structuredClone(s);
39
39
  return t.forEach((e) => {
40
40
  e.errorMessage && (r.errorMessage = e.errorMessage), e.role && (r.role = e.role), e.responseId && (r.responseId = e.responseId), e.content && q(r, e), e.custom_content && (r.custom_content || (r.custom_content = {}), e.custom_content.attachments && (r.custom_content.attachments || (r.custom_content.attachments = []), r.custom_content.attachments = r.custom_content.attachments.concat(
41
41
  e.custom_content.attachments
42
- )), e.custom_content.stages && (r.custom_content.stages || (r.custom_content.stages = []), r.custom_content.stages = w(
42
+ )), e.custom_content.stages && (r.custom_content.stages || (r.custom_content.stages = []), r.custom_content.stages = b(
43
43
  r.custom_content.stages,
44
44
  e.custom_content.stages
45
45
  )), e.custom_content.state && (r.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (r.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (r.custom_content.form_value = e.custom_content.form_value));
46
46
  }), r;
47
47
  };
48
- function q(n, t) {
48
+ function q(s, t) {
49
49
  if (t.content) {
50
- const r = b(t.content);
51
- r != null ? n.content = n.content.slice(0, -r) : n.content = `${n.content || ""}${t.content}`;
50
+ const r = v(t.content);
51
+ r != null ? s.content = s.content.slice(0, -r) : s.content = `${s.content || ""}${t.content}`;
52
52
  }
53
53
  }
54
- function b(n) {
55
- const t = n.match(/delete_chars\((\d+)\)/);
54
+ function v(s) {
55
+ const t = s.match(/delete_chars\((\d+)\)/);
56
56
  return t != null ? parseInt(t[1], 10) : null;
57
57
  }
58
- const v = {
58
+ const V = {
59
59
  CHAT: "/api/chat"
60
- }, V = "application/json", x = "Content-Type", R = "Api-Key", P = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key", H = (n) => (n == null ? void 0 : n.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ")) || "", S = (n, t, r) => {
60
+ }, x = "application/json", P = "Content-Type", R = "Api-Key", H = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
61
+ class _ extends Error {
62
+ constructor(t) {
63
+ super(t.message), this.name = "HttpError", this.status = t.status, this.details = t.details;
64
+ }
65
+ }
66
+ const D = (s) => (s == null ? void 0 : s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ")) || "", S = (s, t, r) => {
61
67
  const e = {
62
- [x]: (t == null ? void 0 : t.contentType) || V
68
+ [P]: (t == null ? void 0 : t.contentType) || x
63
69
  };
64
- return t != null && t.jwt ? e.Authorization = `Bearer ${t.jwt}` : n && (e[R] = n), t != null && t.chatReference && (e[P] = t.chatReference), { ...e, ...r };
65
- }, D = (n) => {
66
- const t = { ...n };
70
+ return t != null && t.jwt ? e.Authorization = `Bearer ${t.jwt}` : s && (e[R] = s), t != null && t.chatReference && (e[H] = t.chatReference), { ...e, ...r };
71
+ }, L = (s) => {
72
+ const t = { ...s };
67
73
  return t[R] && (t[R] = t[R].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[I] && (t[I] = t[I].substring(0, 8) + "...[REDACTED]"), t;
68
- }, L = (n) => ({
69
- "Content-Type": `multipart/form-data; boundary=${n}`
70
- }), U = (n) => {
71
- var s;
72
- const t = ((s = n.name) == null ? void 0 : s.split("__")) || [], r = t.length > 1 ? t.slice(1).join("__") : n.name;
74
+ }, U = (s) => ({
75
+ "Content-Type": `multipart/form-data; boundary=${s}`
76
+ }), j = (s) => {
77
+ var n;
78
+ const t = ((n = s.name) == null ? void 0 : n.split("__")) || [], r = t.length > 1 ? t.slice(1).join("__") : s.name;
73
79
  return { modelId: t[0], conversationName: r };
74
- }, j = (n) => {
75
- const t = Date.now(), r = H(n.name);
76
- return `${n.folderId}/${r}-${t}`;
77
- }, F = (n) => ({ resourceTypes: [_.CONVERSATION], with: n }), O = async (n, t, r) => await fetch(n, {
80
+ }, k = (s) => {
81
+ const t = Date.now(), r = D(s.name);
82
+ return `${s.folderId}/${r}-${t}`;
83
+ }, M = (s) => ({ resourceTypes: [C.CONVERSATION], with: s }), O = async (s, t, r) => await fetch(s, {
78
84
  method: r.method || "GET",
79
85
  headers: t,
80
86
  body: r != null && r.isFormData && typeof (r == null ? void 0 : r.body) == "string" ? r.body : JSON.stringify(r.body),
81
87
  signal: r == null ? void 0 : r.signal
82
88
  });
83
- function h(n) {
84
- return n.split("/").map((t) => encodeURIComponent(t)).join("/");
89
+ function h(s) {
90
+ return s.split("/").map((t) => encodeURIComponent(t)).join("/");
85
91
  }
86
- function M(n) {
87
- return n.split("/").map((t) => decodeURIComponent(t)).join("/");
92
+ function J(s) {
93
+ return s.split("/").map((t) => decodeURIComponent(t)).join("/");
88
94
  }
89
- class k {
95
+ class K {
90
96
  constructor() {
91
97
  this.decoder = new TextDecoder();
92
98
  }
93
- async streamChat(t, r, e = {}, s) {
94
- const { onMessage: o, onError: c, onComplete: a, signal: d } = e;
99
+ async streamChat(t, r, e = {}, n) {
100
+ const { onMessage: o, onError: c, onComplete: a, signal: i } = e;
95
101
  try {
96
- const i = await this.initializeStreamRequest(
102
+ const d = await this.initializeStreamRequest(
97
103
  t,
98
104
  r,
99
- d,
100
- s
105
+ i,
106
+ n
101
107
  );
102
- await this.processStreamData(i, o), a == null || a();
103
- } catch (i) {
104
- this.handleStreamError(i, c);
108
+ await this.processStreamData(d, o), a == null || a();
109
+ } catch (d) {
110
+ this.handleStreamError(d, c);
105
111
  }
106
112
  }
107
- async initializeStreamRequest(t, r, e, s) {
113
+ async initializeStreamRequest(t, r, e, n) {
108
114
  const o = S(void 0, {
109
- jwt: s
115
+ jwt: n
110
116
  }), c = await O(
111
117
  t,
112
118
  {
@@ -121,20 +127,30 @@ class k {
121
127
  );
122
128
  if (!c.ok) {
123
129
  const a = await c.text();
124
- throw new Error(
125
- JSON.stringify({ status: c.status, message: a })
126
- );
130
+ let i = {};
131
+ try {
132
+ i = JSON.parse(a);
133
+ } catch {
134
+ i.message = "Failed to parse error body";
135
+ }
136
+ throw new _({
137
+ status: c.status,
138
+ message: i.message ?? "No response body"
139
+ });
127
140
  }
128
141
  if (!c.body)
129
- throw new Error("No response body");
142
+ throw new _({
143
+ message: "No response body",
144
+ status: c.status
145
+ });
130
146
  return c.body.getReader();
131
147
  }
132
148
  async processStreamData(t, r) {
133
149
  let e = "";
134
150
  try {
135
151
  for (; ; ) {
136
- const { done: s, value: o } = await t.read();
137
- if (s) {
152
+ const { done: n, value: o } = await t.read();
153
+ if (n) {
138
154
  e.trim() && this.parseSSEDataLine(e, r);
139
155
  break;
140
156
  }
@@ -143,8 +159,8 @@ class k {
143
159
  const a = e.split(`
144
160
  `);
145
161
  e = a.pop() || "";
146
- for (const d of a)
147
- this.parseSSEDataLine(d, r);
162
+ for (const i of a)
163
+ this.parseSSEDataLine(i, r);
148
164
  }
149
165
  } finally {
150
166
  t.releaseLock();
@@ -157,56 +173,56 @@ class k {
157
173
  parseSSEDataLine(t, r) {
158
174
  const e = t.trim();
159
175
  if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
160
- const s = e.slice(6);
161
- if (s === "[DONE]") {
176
+ const n = e.slice(6);
177
+ if (n === "[DONE]") {
162
178
  console.info("SSE: Stream completed");
163
179
  return;
164
180
  }
165
181
  try {
166
- const o = JSON.parse(s);
182
+ const o = JSON.parse(n);
167
183
  r == null || r(o);
168
184
  } catch (o) {
169
- console.error(`Failed to parse SSE data: ${s} ${o}`);
185
+ console.error(`Failed to parse SSE data: ${n} ${o}`);
170
186
  }
171
187
  }
172
188
  }
173
189
  }
174
- const K = new k(), J = async (n, t, r, e, s) => {
175
- const { onMessage: o, onToken: c, onComplete: a, onError: d, model: i, signal: l } = r, A = {
176
- conversationId: n,
190
+ const F = new K(), z = async (s, t, r, e, n) => {
191
+ const { onMessage: o, onToken: c, onComplete: a, onError: i, model: d, signal: l } = r, A = {
192
+ conversationId: s,
177
193
  messages: t,
178
- model: i,
179
- custom_fields: s
194
+ model: d,
195
+ custom_fields: n
180
196
  };
181
- await K.streamChat(
182
- v.CHAT,
197
+ await F.streamChat(
198
+ V.CHAT,
183
199
  A,
184
200
  {
185
- onMessage: (C) => p(C, o, c),
201
+ onMessage: (N) => g(N, o, c),
186
202
  onComplete: a,
187
- onError: d,
203
+ onError: i,
188
204
  signal: l
189
205
  },
190
206
  e
191
207
  );
192
- }, m = (n) => n instanceof Error && n.message.includes("404"), f = (n) => `/v1/conversations/${h(n)}`;
193
- class z {
208
+ }, m = (s) => s instanceof Error && s.message.includes("404"), f = (s) => `/v1/conversations/${h(s)}`;
209
+ class G {
194
210
  constructor(t) {
195
211
  this.client = t;
196
212
  }
197
213
  async getConversations(t, r, e) {
198
- const s = `${r ? e ? `${r}/${e}` : `${r}` : ""}`, o = `${u.CONVERSATIONS}/${s}`;
214
+ const n = `${r ? e ? `${r}/${e}` : `${r}` : ""}`, o = `${u.CONVERSATIONS}/${n}`;
199
215
  try {
200
216
  return (await this.client.getRequest(o + "/?limit=1000&recursive=false", t).then((a) => a.items || [])).map((a) => {
201
217
  var l;
202
- const { conversationName: d, modelId: i } = U(a);
218
+ const { conversationName: i, modelId: d } = j(a);
203
219
  return {
204
220
  id: ((l = a.url) == null ? void 0 : l.replace("conversations/", "")) || a.name,
205
- name: d,
206
- folderId: s,
221
+ name: i,
222
+ folderId: n,
207
223
  createdAt: a.createdAt,
208
224
  updatedAt: a.updatedAt,
209
- model: { id: i, name: i }
225
+ model: { id: d, name: d }
210
226
  };
211
227
  });
212
228
  } catch (c) {
@@ -237,9 +253,9 @@ class z {
237
253
  throw e;
238
254
  }
239
255
  }
240
- async putOnboardingFile(t, r, e, s) {
256
+ async putOnboardingFile(t, r, e, n) {
241
257
  try {
242
- const o = `${u.VERSION}/${h(r)}`, c = "----NodeMultipartBoundary", d = [
258
+ const o = `${u.VERSION}/${h(r)}`, c = "----NodeMultipartBoundary", i = [
243
259
  `--${c}`,
244
260
  `Content-Disposition: form-data; name="file"; filename="${t}"`,
245
261
  "Content-Type: application/json",
@@ -249,10 +265,10 @@ class z {
249
265
  ""
250
266
  ].join(`\r
251
267
  `);
252
- return await this.client.request(o, s, {
268
+ return await this.client.request(o, n, {
253
269
  method: "PUT",
254
- body: d,
255
- headers: L(c),
270
+ body: i,
271
+ headers: U(c),
256
272
  isFormData: !0
257
273
  });
258
274
  } catch (o) {
@@ -282,9 +298,9 @@ class z {
282
298
  }
283
299
  }
284
300
  async createConversation(t, r) {
285
- const e = (t == null ? void 0 : t.id) || j(t), { name: s, folderId: o, model: c, messages: a, custom_fields: d } = t, i = {
301
+ const e = (t == null ? void 0 : t.id) || k(t), { name: n, folderId: o, model: c, messages: a, custom_fields: i } = t, d = {
286
302
  id: e,
287
- name: s,
303
+ name: n,
288
304
  folderId: o,
289
305
  model: c,
290
306
  messages: a || [],
@@ -293,22 +309,22 @@ class z {
293
309
  temperature: t.temperature || 0.7,
294
310
  createdAt: Date.now(),
295
311
  updatedAt: Date.now(),
296
- custom_fields: d
312
+ custom_fields: i
297
313
  };
298
314
  return await this.client.request(
299
315
  f(e),
300
316
  r,
301
317
  {
302
318
  method: "PUT",
303
- body: i
319
+ body: d
304
320
  }
305
321
  ), {
306
322
  id: e,
307
- name: s,
323
+ name: n,
308
324
  folderId: o,
309
325
  model: c,
310
- createdAt: i.createdAt,
311
- updatedAt: i.updatedAt
326
+ createdAt: d.createdAt,
327
+ updatedAt: d.updatedAt
312
328
  };
313
329
  }
314
330
  async generateConversationLink(t, r) {
@@ -339,11 +355,11 @@ class z {
339
355
  );
340
356
  }
341
357
  async updateConversation(t, r, e) {
342
- const s = await this.getConversation(t, e);
343
- if (!s)
358
+ const n = await this.getConversation(t, e);
359
+ if (!n)
344
360
  throw new Error(`Conversation with id ${t} not found`);
345
361
  const o = {
346
- ...s,
362
+ ...n,
347
363
  ...r,
348
364
  updatedAt: Date.now()
349
365
  };
@@ -374,7 +390,7 @@ class z {
374
390
  });
375
391
  }
376
392
  async streamChat(t, r) {
377
- const e = t.model.id, s = encodeURIComponent(e), o = `${u.CHAT(s)}?api-version=${this.client.config.version}`, c = {
393
+ const e = t.model.id, n = encodeURIComponent(e), o = `${u.CHAT(n)}?api-version=${this.client.config.version}`, c = {
378
394
  messages: t.messages,
379
395
  stream: !0,
380
396
  temperature: 0.7,
@@ -387,10 +403,10 @@ class z {
387
403
  chatReference: t.conversationId
388
404
  });
389
405
  }
390
- async rateResponse(t, r, e, s) {
406
+ async rateResponse(t, r, e, n) {
391
407
  return await this.client.postRequest(
392
408
  u.RATE(t),
393
- s,
409
+ n,
394
410
  {
395
411
  body: {
396
412
  responseId: r,
@@ -409,7 +425,7 @@ class z {
409
425
  });
410
426
  }
411
427
  }
412
- class G {
428
+ class Y {
413
429
  constructor(t) {
414
430
  this.config = t, console.info("DialApiClient initialized", {
415
431
  host: t.host || "NOT SET",
@@ -424,7 +440,7 @@ class G {
424
440
  return this.request(t, r, { ...e, method: "POST" });
425
441
  }
426
442
  async requestBlob(t, r, e) {
427
- const s = `${this.config.host}${t}`, o = {
443
+ const n = `${this.config.host}${t}`, o = {
428
444
  ...S(this.config.apiKey, {
429
445
  jwt: r,
430
446
  chatReference: e.chatReference
@@ -432,17 +448,17 @@ class G {
432
448
  ...e.headers
433
449
  };
434
450
  try {
435
- return (await O(s, o, e)).blob();
451
+ return (await O(n, o, e)).blob();
436
452
  } catch (c) {
437
453
  throw console.error("API Request Exception", {
438
454
  method: e.method,
439
- url: s,
455
+ url: n,
440
456
  error: c instanceof Error ? c.message : String(c)
441
457
  }), c;
442
458
  }
443
459
  }
444
460
  async request(t, r, e) {
445
- const s = Date.now(), o = `${this.config.host}${t}`, c = {
461
+ const n = Date.now(), o = `${this.config.host}${t}`, c = {
446
462
  ...S(this.config.apiKey, {
447
463
  jwt: r,
448
464
  chatReference: e.chatReference
@@ -451,42 +467,42 @@ class G {
451
467
  };
452
468
  this.addInfoRequestLog("API Request", o, e, c);
453
469
  try {
454
- const a = await O(o, c, e), d = Date.now() - s;
455
- let i;
470
+ const a = await O(o, c, e), i = Date.now() - n;
471
+ let d;
456
472
  const l = await a.text();
457
473
  try {
458
- i = l ? JSON.parse(l) : {};
474
+ d = l ? JSON.parse(l) : {};
459
475
  } catch {
460
476
  if (this.addErrorRequestParsing(
461
477
  o,
462
478
  e,
463
479
  a,
464
- d,
480
+ i,
465
481
  l
466
482
  ), !a.ok)
467
483
  throw new Error(
468
484
  `API request failed: ${a.status} ${a.statusText} - ${l.substring(0, 100)}`
469
485
  );
470
- i = { data: l };
486
+ d = { data: l };
471
487
  }
472
488
  if (!a.ok) {
473
- this.addErrorRequestLog(o, e, a, d, i);
474
- const A = g(i, a);
489
+ this.addErrorRequestLog(o, e, a, i, d);
490
+ const A = w(d, a);
475
491
  throw new Error(`API request failed: ${A}`);
476
492
  }
477
- return i;
493
+ return d;
478
494
  } catch (a) {
479
- const d = Date.now() - s;
495
+ const i = Date.now() - n;
480
496
  throw console.error("API Request Exception", {
481
497
  method: e.method,
482
498
  url: o,
483
- duration: `${d}ms`,
499
+ duration: `${i}ms`,
484
500
  error: a instanceof Error ? a.message : String(a)
485
501
  }), a;
486
502
  }
487
503
  }
488
504
  async stream(t, r, e) {
489
- const s = `${this.config.host}${t}`, o = S(
505
+ const n = `${this.config.host}${t}`, o = S(
490
506
  this.config.apiKey,
491
507
  {
492
508
  jwt: r,
@@ -494,12 +510,12 @@ class G {
494
510
  },
495
511
  e.headers
496
512
  );
497
- this.addInfoRequestLog("Stream Request", s, e, o);
498
- const c = await O(s, o, e);
513
+ this.addInfoRequestLog("Stream Request", n, e, o);
514
+ const c = await O(n, o, e);
499
515
  if (!c.ok)
500
516
  throw console.error("Stream Request Failed", {
501
517
  method: e.method || "POST",
502
- url: s,
518
+ url: n,
503
519
  status: c.status,
504
520
  statusText: c.statusText
505
521
  }), new Error(
@@ -509,31 +525,31 @@ class G {
509
525
  throw new Error("No response body for stream");
510
526
  return c.body;
511
527
  }
512
- addInfoRequestLog(t, r, e, s) {
528
+ addInfoRequestLog(t, r, e, n) {
513
529
  const o = {
514
530
  method: e.method || "GET",
515
531
  url: r,
516
- headers: D(s)
532
+ headers: L(n)
517
533
  };
518
534
  e.body && (o.body = e.body), console.info(t, o);
519
535
  }
520
- addErrorRequestLog(t, r, e, s, o) {
536
+ addErrorRequestLog(t, r, e, n, o) {
521
537
  console.error("API Request Failed", {
522
538
  method: r.method,
523
539
  url: t,
524
540
  status: e.status,
525
541
  statusText: e.statusText,
526
- duration: `${s}ms`,
542
+ duration: `${n}ms`,
527
543
  response: o
528
544
  });
529
545
  }
530
- addErrorRequestParsing(t, r, e, s, o) {
546
+ addErrorRequestParsing(t, r, e, n, o) {
531
547
  console.error("API Response Parse Error", {
532
548
  method: r.method,
533
549
  url: t,
534
550
  status: e.status,
535
551
  statusText: e.statusText,
536
- duration: `${s}ms`,
552
+ duration: `${n}ms`,
537
553
  responseText: o.substring(0, 200),
538
554
  // First 200 chars
539
555
  error: "Response is not valid JSON"
@@ -541,23 +557,23 @@ class G {
541
557
  }
542
558
  }
543
559
  export {
544
- y as AttachmentType,
545
- k as ChatStreamSSEClient,
546
- z as ConversationApi,
560
+ p as AttachmentType,
561
+ K as ChatStreamSSEClient,
562
+ G as ConversationApi,
547
563
  u as DIAL_API_ROUTES,
548
- G as DialApiClient,
564
+ Y as DialApiClient,
549
565
  T as InvitationType,
550
- _ as ResourceTypes,
551
- N as ShareTarget,
552
- K as chatStreamSSEClient,
553
- M as decodeApiUrl,
566
+ C as ResourceTypes,
567
+ y as ShareTarget,
568
+ F as chatStreamSSEClient,
569
+ J as decodeApiUrl,
554
570
  h as encodeApiUrl,
555
- j as generateConversationId,
556
- g as getErrorMessage,
557
- F as getSharedConversationsRequest,
558
- p as handleStreamMessage,
571
+ k as generateConversationId,
572
+ w as getErrorMessage,
573
+ M as getSharedConversationsRequest,
574
+ g as handleStreamMessage,
559
575
  B as mergeMessages,
560
- U as parseConversationName,
576
+ j as parseConversationName,
561
577
  O as sendRequest,
562
- J as streamChatResponse
578
+ z as streamChatResponse
563
579
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.2.0-rc.35",
3
+ "version": "0.2.0-rc.37",
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.2.0-rc.35",
17
+ "@epam/statgpt-shared-toolkit": "0.2.0-rc.37",
18
18
  "@epam/ai-dial-shared": "^0.34.0"
19
19
  }
20
20
  }