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