@epam/statgpt-dial-toolkit 0.2.0-rc.11 → 0.2.0-rc.12

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