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

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 +2 -2
  2. package/index.mjs +35 -35
  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: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(`
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||{}),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||{}),g=(s=>(s.LINK="link",s))(g||{});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.isHttpError=!0,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.error="Failed to parse error body"}throw new O({status:a.status,message:i.error??"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
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;
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=T;exports.ChatStreamSSEClient=q;exports.ConversationApi=Y;exports.DIAL_API_ROUTES=u;exports.DialApiClient=W;exports.InvitationType=g;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
@@ -1,4 +1,4 @@
1
- const E = "/v1/ops/resource/share", u = {
1
+ const E = "/v1/ops/resource/share", d = {
2
2
  VERSION: "/v1",
3
3
  BUCKET: "/v1/bucket",
4
4
  CONVERSATIONS: "/v1/metadata/conversations",
@@ -60,7 +60,7 @@ const V = {
60
60
  }, x = "application/json", P = "Content-Type", R = "Api-Key", H = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
61
61
  class _ extends Error {
62
62
  constructor(t) {
63
- super(t.message), this.name = "HttpError", this.status = t.status, this.details = t.details;
63
+ super(t.message), this.isHttpError = !0, this.name = "HttpError", this.status = t.status, this.details = t.details;
64
64
  }
65
65
  }
66
66
  const D = (s) => (s == null ? void 0 : s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ")) || "", S = (s, t, r) => {
@@ -99,15 +99,15 @@ class K {
99
99
  async streamChat(t, r, e = {}, n) {
100
100
  const { onMessage: o, onError: c, onComplete: a, signal: i } = e;
101
101
  try {
102
- const d = await this.initializeStreamRequest(
102
+ const u = await this.initializeStreamRequest(
103
103
  t,
104
104
  r,
105
105
  i,
106
106
  n
107
107
  );
108
- await this.processStreamData(d, o), a == null || a();
109
- } catch (d) {
110
- this.handleStreamError(d, c);
108
+ await this.processStreamData(u, o), a == null || a();
109
+ } catch (u) {
110
+ this.handleStreamError(u, c);
111
111
  }
112
112
  }
113
113
  async initializeStreamRequest(t, r, e, n) {
@@ -131,11 +131,11 @@ class K {
131
131
  try {
132
132
  i = JSON.parse(a);
133
133
  } catch {
134
- i.message = "Failed to parse error body";
134
+ i.error = "Failed to parse error body";
135
135
  }
136
136
  throw new _({
137
137
  status: c.status,
138
- message: i.message ?? "No response body"
138
+ message: i.error ?? "No response body"
139
139
  });
140
140
  }
141
141
  if (!c.body)
@@ -188,10 +188,10 @@ class K {
188
188
  }
189
189
  }
190
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 = {
191
+ const { onMessage: o, onToken: c, onComplete: a, onError: i, model: u, signal: l } = r, A = {
192
192
  conversationId: s,
193
193
  messages: t,
194
- model: d,
194
+ model: u,
195
195
  custom_fields: n
196
196
  };
197
197
  await F.streamChat(
@@ -211,18 +211,18 @@ class G {
211
211
  this.client = t;
212
212
  }
213
213
  async getConversations(t, r, e) {
214
- const n = `${r ? e ? `${r}/${e}` : `${r}` : ""}`, o = `${u.CONVERSATIONS}/${n}`;
214
+ const n = `${r ? e ? `${r}/${e}` : `${r}` : ""}`, o = `${d.CONVERSATIONS}/${n}`;
215
215
  try {
216
216
  return (await this.client.getRequest(o + "/?limit=1000&recursive=false", t).then((a) => a.items || [])).map((a) => {
217
217
  var l;
218
- const { conversationName: i, modelId: d } = j(a);
218
+ const { conversationName: i, modelId: u } = j(a);
219
219
  return {
220
220
  id: ((l = a.url) == null ? void 0 : l.replace("conversations/", "")) || a.name,
221
221
  name: i,
222
222
  folderId: n,
223
223
  createdAt: a.createdAt,
224
224
  updatedAt: a.updatedAt,
225
- model: { id: d, name: d }
225
+ model: { id: u, name: u }
226
226
  };
227
227
  });
228
228
  } catch (c) {
@@ -245,7 +245,7 @@ class G {
245
245
  }
246
246
  async getFile(t, r) {
247
247
  try {
248
- const e = `${u.VERSION}/${h(t)}`;
248
+ const e = `${d.VERSION}/${h(t)}`;
249
249
  return await this.client.getRequest(e, r);
250
250
  } catch (e) {
251
251
  if (m(e))
@@ -255,7 +255,7 @@ class G {
255
255
  }
256
256
  async putOnboardingFile(t, r, e, n) {
257
257
  try {
258
- const o = `${u.VERSION}/${h(r)}`, c = "----NodeMultipartBoundary", i = [
258
+ const o = `${d.VERSION}/${h(r)}`, c = "----NodeMultipartBoundary", i = [
259
259
  `--${c}`,
260
260
  `Content-Disposition: form-data; name="file"; filename="${t}"`,
261
261
  "Content-Type: application/json",
@@ -279,7 +279,7 @@ class G {
279
279
  }
280
280
  async getOnboardingFile(t, r) {
281
281
  try {
282
- const e = `${u.VERSION}/${h(t)}`;
282
+ const e = `${d.VERSION}/${h(t)}`;
283
283
  return await this.client.getRequest(e, r);
284
284
  } catch (e) {
285
285
  if (m(e))
@@ -289,7 +289,7 @@ class G {
289
289
  }
290
290
  async getFileBlob(t, r) {
291
291
  try {
292
- const e = `${u.VERSION}/${h(t)}`;
292
+ const e = `${d.VERSION}/${h(t)}`;
293
293
  return await this.client.requestBlob(e, r, { method: "GET" });
294
294
  } catch (e) {
295
295
  if (m(e))
@@ -298,7 +298,7 @@ class G {
298
298
  }
299
299
  }
300
300
  async createConversation(t, r) {
301
- const e = (t == null ? void 0 : t.id) || k(t), { name: n, folderId: o, model: c, messages: a, custom_fields: i } = t, d = {
301
+ const e = (t == null ? void 0 : t.id) || k(t), { name: n, folderId: o, model: c, messages: a, custom_fields: i } = t, u = {
302
302
  id: e,
303
303
  name: n,
304
304
  folderId: o,
@@ -316,20 +316,20 @@ class G {
316
316
  r,
317
317
  {
318
318
  method: "PUT",
319
- body: d
319
+ body: u
320
320
  }
321
321
  ), {
322
322
  id: e,
323
323
  name: n,
324
324
  folderId: o,
325
325
  model: c,
326
- createdAt: d.createdAt,
327
- updatedAt: d.updatedAt
326
+ createdAt: u.createdAt,
327
+ updatedAt: u.updatedAt
328
328
  };
329
329
  }
330
330
  async generateConversationLink(t, r) {
331
331
  return await this.client.postRequest(
332
- u.SHARE_CONVERSATION,
332
+ d.SHARE_CONVERSATION,
333
333
  t,
334
334
  {
335
335
  body: r
@@ -338,7 +338,7 @@ class G {
338
338
  }
339
339
  async getSharedConversations(t, r) {
340
340
  return await this.client.postRequest(
341
- u.SHARE_CONVERSATION_LIST,
341
+ d.SHARE_CONVERSATION_LIST,
342
342
  t,
343
343
  {
344
344
  body: r
@@ -347,7 +347,7 @@ class G {
347
347
  }
348
348
  async revokeSharedConversations(t, r) {
349
349
  await this.client.postRequest(
350
- u.SHARE_CONVERSATION_REVOKE,
350
+ d.SHARE_CONVERSATION_REVOKE,
351
351
  t,
352
352
  {
353
353
  body: r
@@ -374,7 +374,7 @@ class G {
374
374
  }
375
375
  async deleteConversation(t, r, e) {
376
376
  r != null && r.isShared ? await this.client.postRequest(
377
- u.SHARE_CONVERSATION_DISCARD,
377
+ d.SHARE_CONVERSATION_DISCARD,
378
378
  e,
379
379
  {
380
380
  body: {
@@ -390,7 +390,7 @@ class G {
390
390
  });
391
391
  }
392
392
  async streamChat(t, r) {
393
- const e = t.model.id, n = encodeURIComponent(e), o = `${u.CHAT(n)}?api-version=${this.client.config.version}`, c = {
393
+ const e = t.model.id, n = encodeURIComponent(e), o = `${d.CHAT(n)}?api-version=${this.client.config.version}`, c = {
394
394
  messages: t.messages,
395
395
  stream: !0,
396
396
  temperature: 0.7,
@@ -405,7 +405,7 @@ class G {
405
405
  }
406
406
  async rateResponse(t, r, e, n) {
407
407
  return await this.client.postRequest(
408
- u.RATE(t),
408
+ d.RATE(t),
409
409
  n,
410
410
  {
411
411
  body: {
@@ -416,7 +416,7 @@ class G {
416
416
  );
417
417
  }
418
418
  async renameConversation(t, r, e) {
419
- return await this.client.postRequest(u.RENAME, e, {
419
+ return await this.client.postRequest(d.RENAME, e, {
420
420
  body: {
421
421
  sourceUrl: t,
422
422
  destinationUrl: r,
@@ -468,10 +468,10 @@ class Y {
468
468
  this.addInfoRequestLog("API Request", o, e, c);
469
469
  try {
470
470
  const a = await O(o, c, e), i = Date.now() - n;
471
- let d;
471
+ let u;
472
472
  const l = await a.text();
473
473
  try {
474
- d = l ? JSON.parse(l) : {};
474
+ u = l ? JSON.parse(l) : {};
475
475
  } catch {
476
476
  if (this.addErrorRequestParsing(
477
477
  o,
@@ -483,14 +483,14 @@ class Y {
483
483
  throw new Error(
484
484
  `API request failed: ${a.status} ${a.statusText} - ${l.substring(0, 100)}`
485
485
  );
486
- d = { data: l };
486
+ u = { data: l };
487
487
  }
488
488
  if (!a.ok) {
489
- this.addErrorRequestLog(o, e, a, i, d);
490
- const A = w(d, a);
489
+ this.addErrorRequestLog(o, e, a, i, u);
490
+ const A = w(u, a);
491
491
  throw new Error(`API request failed: ${A}`);
492
492
  }
493
- return d;
493
+ return u;
494
494
  } catch (a) {
495
495
  const i = Date.now() - n;
496
496
  throw console.error("API Request Exception", {
@@ -560,7 +560,7 @@ export {
560
560
  p as AttachmentType,
561
561
  K as ChatStreamSSEClient,
562
562
  G as ConversationApi,
563
- u as DIAL_API_ROUTES,
563
+ d as DIAL_API_ROUTES,
564
564
  Y as DialApiClient,
565
565
  T as InvitationType,
566
566
  C as ResourceTypes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.2.0-rc.37",
3
+ "version": "0.2.0-rc.39",
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.37",
17
+ "@epam/statgpt-shared-toolkit": "0.2.0-rc.39",
18
18
  "@epam/ai-dial-shared": "^0.34.0"
19
19
  }
20
20
  }