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

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