@epam/statgpt-dial-toolkit 0.3.0-rc.0 → 0.3.0-rc.10

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.
@@ -19,6 +19,7 @@ export declare class ConversationApi {
19
19
  putOnboardingFile(fileName: string, filePath: string, fileData: OnboardingFileSchema, token: string): Promise<Entity | null>;
20
20
  getOnboardingFile(filePath: string, token: string): Promise<OnboardingFileSchema | null>;
21
21
  getFileBlob(filePath: string, token: string): Promise<Blob | null>;
22
+ deleteFile(filePath: string, token: string): Promise<void>;
22
23
  createConversation(data: CreateConversationRequest, token: string): Promise<ConversationInfo>;
23
24
  generateConversationLink(token: string, conversationData?: ConversationData): Promise<GeneratedLinkResponse>;
24
25
  getSharedConversations(token: string, requestData?: SharedConversationsRequest): Promise<SharedConversations>;
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m="v1",f=`/${m}/ops/resource/share`,d={VERSION:`/${m}`,BUCKET:`/${m}/bucket`,CONVERSATIONS:`/${m}/metadata/conversations`,CONVERSATION_BY_ID:n=>`/${m}/metadata/conversations/${n}`,CHAT:n=>`/openai/deployments/${n}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:n=>`/${m}/deployments/${n}/configuration`,DATASETS_METADATA:n=>`/v1/deployments/${n}/route/metadata/datasets`,SHARE_CONVERSATION:`${f}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${m}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${m}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${f}/list`,SHARE_CONVERSATION_DISCARD:`${f}/discard`,SHARE_CONVERSATION_REVOKE:`${f}/revoke`,RATE:n=>`/${m}/${n}/rate`,RENAME:`/${m}/ops/resource/move`},H={LENGTH:"length",STOP:"stop"},R={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},U={CONTENT_FILTER:"content_filter",500:"500"},x={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},V=[R.MINUTE,R.DAILY,R.WEEKLY,R.MONTHLY],K="statgpt",g={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(n=>(n.CONVERSATION="CONVERSATION",n))(O||{}),N=(n=>(n.ME="me",n.OTHERS="others",n))(N||{}),y=(n=>(n.CSV="text/csv",n.TABLE="application/dial-ttyd-table",n.PLOTLY="application/vnd.plotly.v1+json",n.MARKDOWN="text/markdown",n.JSON="application/json",n.JPEG="image/jpeg",n.PNG="image/png",n.CUSTOM_DATA_GRID="custom_data_grid",n.CUSTOM_CHART="custom_chart",n.CUSTOM_CODE_SAMPLE="custom_code_sample",n))(y||{}),$=(n=>(n.LINK="link",n))($||{});const j=n=>n.content?(console.info(`Using direct content format: ${n.content}`),n.content):n.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`),n.choices[0].delta.content):n.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${n.choices[0].message.content}`),n.choices[0].message.content):(console.info("Unknown SSE data format:",n),null),v=(n,t,s)=>{if(t?.(n),s){const e=j(n);e&&s(e)}},D=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,k=(n,t)=>{const s=n?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{s[e.index]?(e.attachments&&(s[e.index].attachments=(s[e.index].attachments||[]).concat(e.attachments)),e.content&&(s[e.index].content=(s[e.index].content||"")+e.content),e.name&&(s[e.index].name=(s[e.index].name||"")+e.name),e.status&&(s[e.index].status=e.status)):s[e.index]=e}),Object.values(s)},F=(n,t)=>{const s=structuredClone(n);return t.forEach(e=>{e.errorMessage&&(s.errorMessage=e.errorMessage),e.role&&(s.role=e.role),e.responseId&&(s.responseId=e.responseId),e.content&&Y(s,e),e.custom_content&&(s.custom_content||(s.custom_content={}),e.custom_content.attachments&&(s.custom_content.attachments||(s.custom_content.attachments=[]),s.custom_content.attachments=s.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(s.custom_content.stages||(s.custom_content.stages=[]),s.custom_content.stages=k(s.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(s.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(s.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(s.custom_content.form_value=e.custom_content.form_value))}),s};function Y(n,t){if(t.content){const s=B(t.content);s!=null?n.content=n.content.slice(0,-s):n.content=`${n.content||""}${t.content}`}}function B(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const G={CHAT:"/api/chat"},J="application/json",X="Content-Type",T="Api-Key",z="X-CONVERSATION-ID",I="Ocp-Apim-Subscription-Key";class C 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,this.displayMessage=t.displayMessage}}const W=n=>n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," ")||"",A=(n,t,s)=>{const e={[X]:t?.contentType||J};return t?.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[T]=n),t?.chatReference&&(e[z]=t.chatReference),{...e,...s}},Q=n=>{const t={...n};return t[T]&&(t[T]=t[T].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[I]&&(t[I]=t[I].substring(0,8)+"...[REDACTED]"),t},Z=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),w=n=>{const t=n.name?.split("__")||[],s=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:s}},L=n=>{const t=Date.now(),s=W(n.name);return`${n.folderId}/${s}-${t}`},ee=n=>({resourceTypes:[O.CONVERSATION],with:n}),S=async(n,t,s)=>await fetch(n,{method:s.method||"GET",headers:t,body:s?.isFormData&&typeof s?.body=="string"?s.body:JSON.stringify(s.body),signal:s?.signal});function h(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function te(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}function b(n){if(n?.kind!==g.RATE_LIMIT||typeof n.retryAfterSeconds!="number")return null;const t=new Date(n.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+n.retryAfterSeconds*1e3)}function se(n,t=Date.now()){const s=b(n);return s?s.getTime()>t:!1}function ne(n,t="en-GB"){return{date:n.toLocaleDateString(t),time:n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,s,e={},r){const{onMessage:a,onError:o,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,s,c,r);await this.processStreamData(u,a),i?.()}catch(u){this.handleStreamError(u,o)}}async initializeStreamRequest(t,s,e,r){const a=A(void 0,{jwt:r}),o=await S(t,{Accept:"text/event-stream",...a},{method:"POST",body:s,signal:e});if(!o.ok){const i=await o.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new C({status:o.status,message:c.error??"No response body"})}if(!o.body)throw new C({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,s){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,s);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const i=e.split(`
2
- `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,s)}}finally{t.releaseLock()}}handleStreamError(t,s){const e=t instanceof Error?t:new Error(String(t));throw s?.(e),e}parseSSEDataLine(t,s){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let a;try{a=JSON.parse(r)}catch(o){console.error(`Failed to parse SSE data: ${r} ${o}`)}s?.(a)}}}const M=new q,re=async(n,t,s,e,r)=>{const{onMessage:a,onToken:o,onComplete:i,onError:c,model:u,signal:l}=s,p={conversationId:n,messages:t,model:u,custom_fields:r};await M.streamChat(G.CHAT,p,{onMessage:P=>v(P,a,o),onComplete:i,onError:c,signal:l},e)},E=n=>n instanceof Error&&n.message.includes("404"),_=n=>`/v1/conversations/${h(n)}`;class oe{constructor(t){this.client=t}async getConversations(t,s,e){const r=`${s?e?`${s}/${e}`:`${s}`:""}`,a=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=w(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(o){if(E(o))return[];throw o}}async getConversation(t,s){try{return await this.client.getRequest(_(t),s)}catch(e){if(E(e))return null;throw e}}async getFile(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,s)}catch(e){if(E(e))return null;throw e}}async putOnboardingFile(t,s,e,r){try{const a=`${d.VERSION}/${h(s)}`,o="----NodeMultipartBoundary",c=[`--${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(a,r,{method:"PUT",body:c,headers:Z(o),isFormData:!0})}catch(a){if(E(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,s)}catch(e){if(E(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(E(e))return null;throw e}}async createConversation(t,s){const e=t?.id||L(t),{name:r,folderId:a,model:o,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:a,model:o,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(_(e),s,{method:"PUT",body:u}),{id:e,name:r,folderId:a,model:o,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:s})}async updateConversation(t,s,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...s,updatedAt:Date.now()};return await this.client.request(_(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(_(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${d.CHAT(r)}?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(a,s,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,s,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,overwrite:!0}})}}class ae{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,s,e){return this.request(t,s,{...e,method:"GET"})}async postRequest(t,s,e){return this.request(t,s,{...e,method:"POST"})}async requestBlob(t,s,e){const r=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};try{return(await S(r,a,e)).blob()}catch(o){throw console.error("API Request Exception",{method:e.method,url:r,error:o instanceof Error?o.message:String(o)}),o}}async request(t,s,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const i=await S(a,o,e),c=Date.now()-r;let u;const l=await i.text();try{u=l?JSON.parse(l):{}}catch{if(this.addErrorRequestParsing(a,e,i,c,l),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${l.substring(0,100)}`);u={data:l}}if(!i.ok){this.addErrorRequestLog(a,e,i,c,u);const p=D(u,i);throw new Error(`API request failed: ${p}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,s,e){const r=`${this.config.host}${t}`,a=A(this.config.apiKey,{jwt:s,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",r,e,a);const o=await S(r,a,e);if(!o.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,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,s,e,r){const a={method:e.method||"GET",url:s,headers:Q(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,s,e,r,a){console.error("API Request Failed",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,s,e,r,a){console.error("API Response Parse Error",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=y;exports.COMPLETION_FINISH_REASON=H;exports.CUSTOM_VIEW_STATE_KEY=K;exports.ChatStreamSSEClient=q;exports.ConversationApi=oe;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=U;exports.DIAL_ERROR_TYPES=x;exports.DialApiClient=ae;exports.ERROR_CONTEXT_KIND=g;exports.EXCEEDED_LIMIT=R;exports.EXCEEDED_LIMIT_ORDER=V;exports.InvitationType=$;exports.ResourceTypes=O;exports.ShareTarget=N;exports.chatStreamSSEClient=M;exports.decodeApiUrl=te;exports.encodeApiUrl=h;exports.formatDateTime=ne;exports.generateConversationId=L;exports.getErrorMessage=D;exports.getRateLimitRestoreDate=b;exports.getSharedConversationsRequest=ee;exports.handleStreamMessage=v;exports.isRateLimitStillActive=se;exports.mergeMessages=F;exports.parseConversationName=w;exports.sendRequest=S;exports.streamChatResponse=re;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",f=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:n=>`/${l}/metadata/conversations/${n}`,CHAT:n=>`/openai/deployments/${n}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:n=>`/${l}/deployments/${n}/configuration`,DATASETS_METADATA:n=>`/v1/deployments/${n}/route/metadata/datasets`,SHARE_CONVERSATION:`${f}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${l}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${l}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${f}/list`,SHARE_CONVERSATION_DISCARD:`${f}/discard`,SHARE_CONVERSATION_REVOKE:`${f}/revoke`,RATE:n=>`/${l}/${n}/rate`,RENAME:`/${l}/ops/resource/move`},H={LENGTH:"length",STOP:"stop"},R={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},U={CONTENT_FILTER:"content_filter",500:"500"},x={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},V=[R.MINUTE,R.DAILY,R.WEEKLY,R.MONTHLY],K="statgpt",g={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(n=>(n.CONVERSATION="CONVERSATION",n))(O||{}),N=(n=>(n.ME="me",n.OTHERS="others",n))(N||{}),y=(n=>(n.CSV="text/csv",n.TABLE="application/dial-ttyd-table",n.PLOTLY="application/vnd.plotly.v1+json",n.MARKDOWN="text/markdown",n.JSON="application/json",n.JPEG="image/jpeg",n.PNG="image/png",n.CROSS_DATASET_GRID="cross_dataset_grid",n.CUSTOM_DATA_GRID="custom_data_grid",n.CUSTOM_CHART="custom_chart",n.CUSTOM_CODE_SAMPLE="custom_code_sample",n))(y||{}),$=(n=>(n.LINK="link",n))($||{});const j=n=>n.content?(console.info(`Using direct content format: ${n.content}`),n.content):n.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`),n.choices[0].delta.content):n.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${n.choices[0].message.content}`),n.choices[0].message.content):(console.info("Unknown SSE data format:",n),null),D=(n,t,s)=>{if(t?.(n),s){const e=j(n);e&&s(e)}},v=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,k=(n,t)=>{const s=n?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{s[e.index]?(e.attachments&&(s[e.index].attachments=(s[e.index].attachments||[]).concat(e.attachments)),e.content&&(s[e.index].content=(s[e.index].content||"")+e.content),e.name&&(s[e.index].name=(s[e.index].name||"")+e.name),e.status&&(s[e.index].status=e.status)):s[e.index]=e}),Object.values(s)},F=(n,t)=>{const s=structuredClone(n);return t.forEach(e=>{e.errorMessage&&(s.errorMessage=e.errorMessage),e.role&&(s.role=e.role),e.responseId&&(s.responseId=e.responseId),e.content&&Y(s,e),e.custom_content&&(s.custom_content||(s.custom_content={}),e.custom_content.attachments&&(s.custom_content.attachments||(s.custom_content.attachments=[]),s.custom_content.attachments=s.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(s.custom_content.stages||(s.custom_content.stages=[]),s.custom_content.stages=k(s.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(s.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(s.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(s.custom_content.form_value=e.custom_content.form_value))}),s};function Y(n,t){if(t.content){const s=B(t.content);s!=null?n.content=n.content.slice(0,-s):n.content=`${n.content||""}${t.content}`}}function B(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const G={CHAT:"/api/chat"},J="application/json",X="Content-Type",T="Api-Key",z="X-CONVERSATION-ID",p="Ocp-Apim-Subscription-Key";class C 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,this.displayMessage=t.displayMessage}}const W=n=>n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," ")||"",A=(n,t,s)=>{const e={[X]:t?.contentType||J};return t?.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[T]=n),t?.chatReference&&(e[z]=t.chatReference),{...e,...s}},Q=n=>{const t={...n};return t[T]&&(t[T]=t[T].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t},Z=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),w=n=>{const t=n.name?.split("__")||[],s=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:s}},L=n=>{const t=Date.now(),s=W(n.name);return`${n.folderId}/${s}-${t}`},ee=n=>({resourceTypes:[O.CONVERSATION],with:n}),S=async(n,t,s)=>await fetch(n,{method:s.method||"GET",headers:t,body:s?.isFormData&&typeof s?.body=="string"?s.body:JSON.stringify(s.body),signal:s?.signal});function h(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function te(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}function b(n){if(n?.kind!==g.RATE_LIMIT||typeof n.retryAfterSeconds!="number")return null;const t=new Date(n.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+n.retryAfterSeconds*1e3)}function se(n,t=Date.now()){const s=b(n);return s?s.getTime()>t:!1}function ne(n,t="en-GB"){return{date:n.toLocaleDateString(t),time:n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,s,e={},r){const{onMessage:a,onError:o,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,s,c,r);await this.processStreamData(u,a),i?.()}catch(u){this.handleStreamError(u,o)}}async initializeStreamRequest(t,s,e,r){const a=A(void 0,{jwt:r}),o=await S(t,{Accept:"text/event-stream",...a},{method:"POST",body:s,signal:e});if(!o.ok){const i=await o.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new C({status:o.status,message:c.error??"No response body"})}if(!o.body)throw new C({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,s){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,s);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const i=e.split(`
2
+ `);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,s)}}finally{t.releaseLock()}}handleStreamError(t,s){const e=t instanceof Error?t:new Error(String(t));throw s?.(e),e}parseSSEDataLine(t,s){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let a;try{a=JSON.parse(r)}catch(o){console.error(`Failed to parse SSE data: ${r} ${o}`)}s?.(a)}}}const M=new q,re=async(n,t,s,e,r)=>{const{onMessage:a,onToken:o,onComplete:i,onError:c,model:u,signal:m}=s,I={conversationId:n,messages:t,model:u,custom_fields:r};await M.streamChat(G.CHAT,I,{onMessage:P=>D(P,a,o),onComplete:i,onError:c,signal:m},e)},E=n=>n instanceof Error&&n.message.includes("404"),_=n=>`/v1/conversations/${h(n)}`;class oe{constructor(t){this.client=t}async getConversations(t,s,e){const r=`${s?e?`${s}/${e}`:`${s}`:""}`,a=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=w(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(o){if(E(o))return[];throw o}}async getConversation(t,s){try{return await this.client.getRequest(_(t),s)}catch(e){if(E(e))return null;throw e}}async getFile(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,s)}catch(e){if(E(e))return null;throw e}}async putOnboardingFile(t,s,e,r){try{const a=`${d.VERSION}/${h(s)}`,o="----NodeMultipartBoundary",c=[`--${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(a,r,{method:"PUT",body:c,headers:Z(o),isFormData:!0})}catch(a){if(E(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,s)}catch(e){if(E(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(E(e))return null;throw e}}async deleteFile(t,s){try{const e=`${d.VERSION}/${h(t)}`;await this.client.request(e,s,{method:"DELETE"})}catch(e){if(E(e))return;throw e}}async createConversation(t,s){const e=t?.id||L(t),{name:r,folderId:a,model:o,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:a,model:o,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(_(e),s,{method:"PUT",body:u}),{id:e,name:r,folderId:a,model:o,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:s})}async updateConversation(t,s,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...s,updatedAt:Date.now()};return await this.client.request(_(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(_(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${d.CHAT(r)}?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(a,s,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,s,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,overwrite:!0}})}}class ae{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,s,e){return this.request(t,s,{...e,method:"GET"})}async postRequest(t,s,e){return this.request(t,s,{...e,method:"POST"})}async requestBlob(t,s,e){const r=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};try{return(await S(r,a,e)).blob()}catch(o){throw console.error("API Request Exception",{method:e.method,url:r,error:o instanceof Error?o.message:String(o)}),o}}async request(t,s,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const i=await S(a,o,e),c=Date.now()-r;let u;const m=await i.text();try{u=m?JSON.parse(m):{}}catch{if(this.addErrorRequestParsing(a,e,i,c,m),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${m.substring(0,100)}`);u={data:m}}if(!i.ok){this.addErrorRequestLog(a,e,i,c,u);const I=v(u,i);throw new Error(`API request failed: ${I}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,s,e){const r=`${this.config.host}${t}`,a=A(this.config.apiKey,{jwt:s,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",r,e,a);const o=await S(r,a,e);if(!o.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,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,s,e,r){const a={method:e.method||"GET",url:s,headers:Q(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,s,e,r,a){console.error("API Request Failed",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,s,e,r,a){console.error("API Response Parse Error",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=y;exports.COMPLETION_FINISH_REASON=H;exports.CUSTOM_VIEW_STATE_KEY=K;exports.ChatStreamSSEClient=q;exports.ConversationApi=oe;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=U;exports.DIAL_ERROR_TYPES=x;exports.DialApiClient=ae;exports.ERROR_CONTEXT_KIND=g;exports.EXCEEDED_LIMIT=R;exports.EXCEEDED_LIMIT_ORDER=V;exports.InvitationType=$;exports.ResourceTypes=O;exports.ShareTarget=N;exports.chatStreamSSEClient=M;exports.decodeApiUrl=te;exports.encodeApiUrl=h;exports.formatDateTime=ne;exports.generateConversationId=L;exports.getErrorMessage=v;exports.getRateLimitRestoreDate=b;exports.getSharedConversationsRequest=ee;exports.handleStreamMessage=D;exports.isRateLimitStillActive=se;exports.mergeMessages=F;exports.parseConversationName=w;exports.sendRequest=S;exports.streamChatResponse=re;
package/index.mjs CHANGED
@@ -2,18 +2,18 @@ const h = "/v1/ops/resource/share", d = {
2
2
  VERSION: "/v1",
3
3
  BUCKET: "/v1/bucket",
4
4
  CONVERSATIONS: "/v1/metadata/conversations",
5
- CONVERSATION_BY_ID: (s) => `/v1/metadata/conversations/${s}`,
6
- CHAT: (s) => `/openai/deployments/${s}/chat/completions`,
5
+ CONVERSATION_BY_ID: (n) => `/v1/metadata/conversations/${n}`,
6
+ CHAT: (n) => `/openai/deployments/${n}/chat/completions`,
7
7
  MODELS: "/openai/models",
8
- CONFIGURATION: (s) => `/v1/deployments/${s}/configuration`,
9
- DATASETS_METADATA: (s) => `/v1/deployments/${s}/route/metadata/datasets`,
8
+ CONFIGURATION: (n) => `/v1/deployments/${n}/configuration`,
9
+ DATASETS_METADATA: (n) => `/v1/deployments/${n}/route/metadata/datasets`,
10
10
  SHARE_CONVERSATION: `${h}/create`,
11
- SHARE_CONVERSATION_ACCEPT: (s) => `/v1/invitations/${s}?accept=true`,
12
- SHARE_CONVERSATION_DETAILS: (s) => `/v1/invitations/${s}`,
11
+ SHARE_CONVERSATION_ACCEPT: (n) => `/v1/invitations/${n}?accept=true`,
12
+ SHARE_CONVERSATION_DETAILS: (n) => `/v1/invitations/${n}`,
13
13
  SHARE_CONVERSATION_LIST: `${h}/list`,
14
14
  SHARE_CONVERSATION_DISCARD: `${h}/discard`,
15
15
  SHARE_CONVERSATION_REVOKE: `${h}/revoke`,
16
- RATE: (s) => `/v1/${s}/rate`,
16
+ RATE: (n) => `/v1/${n}/rate`,
17
17
  RENAME: "/v1/ops/resource/move"
18
18
  }, G = {
19
19
  LENGTH: "length",
@@ -38,93 +38,93 @@ const h = "/v1/ops/resource/share", d = {
38
38
  RATE_LIMIT: "rate_limit",
39
39
  UNKNOWN: "unknown"
40
40
  };
41
- var T = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(T || {}), g = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(g || {}), y = /* @__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.CUSTOM_CODE_SAMPLE = "custom_code_sample", s))(y || {}), $ = /* @__PURE__ */ ((s) => (s.LINK = "link", s))($ || {});
42
- const w = (s) => s.content ? (console.info(`Using direct content format: ${s.content}`), s.content) : s.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`), s.choices[0].delta.content) : s.choices?.[0]?.message?.content ? (console.info(
43
- `Using complete message format: ${s.choices[0].message.content}`
44
- ), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null), v = (s, t, n) => {
45
- if (t?.(s), n) {
46
- const e = w(s);
47
- e && n(e);
48
- }
49
- }, D = (s, t) => s.error || s.message || `${t.status} ${t.statusText}`, b = (s, t) => {
50
- const n = s?.reduce(
41
+ var p = /* @__PURE__ */ ((n) => (n.CONVERSATION = "CONVERSATION", n))(p || {}), g = /* @__PURE__ */ ((n) => (n.ME = "me", n.OTHERS = "others", n))(g || {}), y = /* @__PURE__ */ ((n) => (n.CSV = "text/csv", n.TABLE = "application/dial-ttyd-table", n.PLOTLY = "application/vnd.plotly.v1+json", n.MARKDOWN = "text/markdown", n.JSON = "application/json", n.JPEG = "image/jpeg", n.PNG = "image/png", n.CROSS_DATASET_GRID = "cross_dataset_grid", n.CUSTOM_DATA_GRID = "custom_data_grid", n.CUSTOM_CHART = "custom_chart", n.CUSTOM_CODE_SAMPLE = "custom_code_sample", n))(y || {}), $ = /* @__PURE__ */ ((n) => (n.LINK = "link", n))($ || {});
42
+ const w = (n) => n.content ? (console.info(`Using direct content format: ${n.content}`), n.content) : n.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`), n.choices[0].delta.content) : n.choices?.[0]?.message?.content ? (console.info(
43
+ `Using complete message format: ${n.choices[0].message.content}`
44
+ ), n.choices[0].message.content) : (console.info("Unknown SSE data format:", n), null), v = (n, t, s) => {
45
+ if (t?.(n), s) {
46
+ const e = w(n);
47
+ e && s(e);
48
+ }
49
+ }, D = (n, t) => n.error || n.message || `${t.status} ${t.statusText}`, b = (n, t) => {
50
+ const s = n?.reduce(
51
51
  (e, r) => (e[r.index] = r, e),
52
52
  {}
53
53
  );
54
54
  return t.forEach((e) => {
55
- n[e.index] ? (e.attachments && (n[e.index].attachments = (n[e.index].attachments || []).concat(e.attachments)), e.content && (n[e.index].content = (n[e.index].content || "") + e.content), e.name && (n[e.index].name = (n[e.index].name || "") + e.name), e.status && (n[e.index].status = e.status)) : n[e.index] = e;
56
- }), Object.values(n);
57
- }, Q = (s, t) => {
58
- const n = structuredClone(s);
55
+ s[e.index] ? (e.attachments && (s[e.index].attachments = (s[e.index].attachments || []).concat(e.attachments)), e.content && (s[e.index].content = (s[e.index].content || "") + e.content), e.name && (s[e.index].name = (s[e.index].name || "") + e.name), e.status && (s[e.index].status = e.status)) : s[e.index] = e;
56
+ }), Object.values(s);
57
+ }, Q = (n, t) => {
58
+ const s = structuredClone(n);
59
59
  return t.forEach((e) => {
60
- e.errorMessage && (n.errorMessage = e.errorMessage), e.role && (n.role = e.role), e.responseId && (n.responseId = e.responseId), e.content && q(n, e), e.custom_content && (n.custom_content || (n.custom_content = {}), e.custom_content.attachments && (n.custom_content.attachments || (n.custom_content.attachments = []), n.custom_content.attachments = n.custom_content.attachments.concat(
60
+ e.errorMessage && (s.errorMessage = e.errorMessage), e.role && (s.role = e.role), e.responseId && (s.responseId = e.responseId), e.content && q(s, e), e.custom_content && (s.custom_content || (s.custom_content = {}), e.custom_content.attachments && (s.custom_content.attachments || (s.custom_content.attachments = []), s.custom_content.attachments = s.custom_content.attachments.concat(
61
61
  e.custom_content.attachments
62
- )), e.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = b(
63
- n.custom_content.stages,
62
+ )), e.custom_content.stages && (s.custom_content.stages || (s.custom_content.stages = []), s.custom_content.stages = b(
63
+ s.custom_content.stages,
64
64
  e.custom_content.stages
65
- )), e.custom_content.state && (n.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (n.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (n.custom_content.form_value = e.custom_content.form_value));
66
- }), n;
65
+ )), e.custom_content.state && (s.custom_content.state = e.custom_content.state), e.custom_content.form_schema && (s.custom_content.form_schema = e.custom_content.form_schema), e.custom_content.form_value && (s.custom_content.form_value = e.custom_content.form_value));
66
+ }), s;
67
67
  };
68
- function q(s, t) {
68
+ function q(n, t) {
69
69
  if (t.content) {
70
- const n = L(t.content);
71
- n != null ? s.content = s.content.slice(0, -n) : s.content = `${s.content || ""}${t.content}`;
70
+ const s = L(t.content);
71
+ s != null ? n.content = n.content.slice(0, -s) : n.content = `${n.content || ""}${t.content}`;
72
72
  }
73
73
  }
74
- function L(s) {
75
- const t = s.match(/delete_chars\((\d+)\)/);
74
+ function L(n) {
75
+ const t = n.match(/delete_chars\((\d+)\)/);
76
76
  return t != null ? parseInt(t[1], 10) : null;
77
77
  }
78
78
  const V = {
79
79
  CHAT: "/api/chat"
80
- }, M = "application/json", P = "Content-Type", S = "Api-Key", H = "X-CONVERSATION-ID", p = "Ocp-Apim-Subscription-Key";
81
- class A extends Error {
80
+ }, M = "application/json", P = "Content-Type", S = "Api-Key", H = "X-CONVERSATION-ID", A = "Ocp-Apim-Subscription-Key";
81
+ class T extends Error {
82
82
  constructor(t) {
83
83
  super(t.message), this.isHttpError = !0, this.name = "HttpError", this.code = t.code, this.status = t.status, this.details = t.details, this.displayMessage = t.displayMessage;
84
84
  }
85
85
  }
86
- const x = (s) => s?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ") || "", _ = (s, t, n) => {
86
+ const x = (n) => n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ") || "", _ = (n, t, s) => {
87
87
  const e = {
88
88
  [P]: t?.contentType || M
89
89
  };
90
- return t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : s && (e[S] = s), t?.chatReference && (e[H] = t.chatReference), { ...e, ...n };
91
- }, U = (s) => {
92
- const t = { ...s };
93
- return t[S] && (t[S] = t[S].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[p] && (t[p] = t[p].substring(0, 8) + "...[REDACTED]"), t;
94
- }, K = (s) => ({
95
- "Content-Type": `multipart/form-data; boundary=${s}`
96
- }), j = (s) => {
97
- const t = s.name?.split("__") || [], n = t.length > 1 ? t.slice(1).join("__") : s.name;
98
- return { modelId: t[0], conversationName: n };
99
- }, k = (s) => {
100
- const t = Date.now(), n = x(s.name);
101
- return `${s.folderId}/${n}-${t}`;
102
- }, Z = (s) => ({ resourceTypes: [T.CONVERSATION], with: s }), I = async (s, t, n) => await fetch(s, {
103
- method: n.method || "GET",
90
+ return t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : n && (e[S] = n), t?.chatReference && (e[H] = t.chatReference), { ...e, ...s };
91
+ }, U = (n) => {
92
+ const t = { ...n };
93
+ return t[S] && (t[S] = t[S].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[A] && (t[A] = t[A].substring(0, 8) + "...[REDACTED]"), t;
94
+ }, K = (n) => ({
95
+ "Content-Type": `multipart/form-data; boundary=${n}`
96
+ }), j = (n) => {
97
+ const t = n.name?.split("__") || [], s = t.length > 1 ? t.slice(1).join("__") : n.name;
98
+ return { modelId: t[0], conversationName: s };
99
+ }, k = (n) => {
100
+ const t = Date.now(), s = x(n.name);
101
+ return `${n.folderId}/${s}-${t}`;
102
+ }, Z = (n) => ({ resourceTypes: [p.CONVERSATION], with: n }), I = async (n, t, s) => await fetch(n, {
103
+ method: s.method || "GET",
104
104
  headers: t,
105
- body: n?.isFormData && typeof n?.body == "string" ? n.body : JSON.stringify(n.body),
106
- signal: n?.signal
105
+ body: s?.isFormData && typeof s?.body == "string" ? s.body : JSON.stringify(s.body),
106
+ signal: s?.signal
107
107
  });
108
- function E(s) {
109
- return s.split("/").map((t) => encodeURIComponent(t)).join("/");
108
+ function E(n) {
109
+ return n.split("/").map((t) => encodeURIComponent(t)).join("/");
110
110
  }
111
- function ee(s) {
112
- return s.split("/").map((t) => decodeURIComponent(t)).join("/");
111
+ function ee(n) {
112
+ return n.split("/").map((t) => decodeURIComponent(t)).join("/");
113
113
  }
114
- function F(s) {
115
- if (s?.kind !== C.RATE_LIMIT || typeof s.retryAfterSeconds != "number")
114
+ function F(n) {
115
+ if (n?.kind !== C.RATE_LIMIT || typeof n.retryAfterSeconds != "number")
116
116
  return null;
117
- const t = new Date(s.occurredAt).getTime();
118
- return Number.isNaN(t) ? null : new Date(t + s.retryAfterSeconds * 1e3);
117
+ const t = new Date(n.occurredAt).getTime();
118
+ return Number.isNaN(t) ? null : new Date(t + n.retryAfterSeconds * 1e3);
119
119
  }
120
- function te(s, t = Date.now()) {
121
- const n = F(s);
122
- return n ? n.getTime() > t : !1;
120
+ function te(n, t = Date.now()) {
121
+ const s = F(n);
122
+ return s ? s.getTime() > t : !1;
123
123
  }
124
- function ne(s, t = "en-GB") {
124
+ function se(n, t = "en-GB") {
125
125
  return {
126
- date: s.toLocaleDateString(t),
127
- time: s.toLocaleTimeString(t, {
126
+ date: n.toLocaleDateString(t),
127
+ time: n.toLocaleTimeString(t, {
128
128
  hour: "2-digit",
129
129
  minute: "2-digit"
130
130
  })
@@ -134,12 +134,12 @@ class Y {
134
134
  constructor() {
135
135
  this.decoder = new TextDecoder();
136
136
  }
137
- async streamChat(t, n, e = {}, r) {
137
+ async streamChat(t, s, e = {}, r) {
138
138
  const { onMessage: a, onError: o, onComplete: c, signal: i } = e;
139
139
  try {
140
140
  const u = await this.initializeStreamRequest(
141
141
  t,
142
- n,
142
+ s,
143
143
  i,
144
144
  r
145
145
  );
@@ -148,7 +148,7 @@ class Y {
148
148
  this.handleStreamError(u, o);
149
149
  }
150
150
  }
151
- async initializeStreamRequest(t, n, e, r) {
151
+ async initializeStreamRequest(t, s, e, r) {
152
152
  const a = _(void 0, {
153
153
  jwt: r
154
154
  }), o = await I(
@@ -159,7 +159,7 @@ class Y {
159
159
  },
160
160
  {
161
161
  method: "POST",
162
- body: n,
162
+ body: s,
163
163
  signal: e
164
164
  }
165
165
  );
@@ -171,25 +171,25 @@ class Y {
171
171
  } catch {
172
172
  i.error = "Failed to parse error body";
173
173
  }
174
- throw new A({
174
+ throw new T({
175
175
  status: o.status,
176
176
  message: i.error ?? "No response body"
177
177
  });
178
178
  }
179
179
  if (!o.body)
180
- throw new A({
180
+ throw new T({
181
181
  message: "No response body",
182
182
  status: o.status
183
183
  });
184
184
  return o.body.getReader();
185
185
  }
186
- async processStreamData(t, n) {
186
+ async processStreamData(t, s) {
187
187
  let e = "";
188
188
  try {
189
189
  for (; ; ) {
190
190
  const { done: r, value: a } = await t.read();
191
191
  if (r) {
192
- e.trim() && this.parseSSEDataLine(e, n);
192
+ e.trim() && this.parseSSEDataLine(e, s);
193
193
  break;
194
194
  }
195
195
  const o = this.decoder.decode(a, { stream: !0 });
@@ -198,17 +198,17 @@ class Y {
198
198
  `);
199
199
  e = c.pop() || "";
200
200
  for (const i of c)
201
- this.parseSSEDataLine(i, n);
201
+ this.parseSSEDataLine(i, s);
202
202
  }
203
203
  } finally {
204
204
  t.releaseLock();
205
205
  }
206
206
  }
207
- handleStreamError(t, n) {
207
+ handleStreamError(t, s) {
208
208
  const e = t instanceof Error ? t : new Error(String(t));
209
- throw n?.(e), e;
209
+ throw s?.(e), e;
210
210
  }
211
- parseSSEDataLine(t, n) {
211
+ parseSSEDataLine(t, s) {
212
212
  const e = t.trim();
213
213
  if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
214
214
  const r = e.slice(6);
@@ -222,13 +222,13 @@ class Y {
222
222
  } catch (o) {
223
223
  console.error(`Failed to parse SSE data: ${r} ${o}`);
224
224
  }
225
- n?.(a);
225
+ s?.(a);
226
226
  }
227
227
  }
228
228
  }
229
- const B = new Y(), se = async (s, t, n, e, r) => {
230
- const { onMessage: a, onToken: o, onComplete: c, onError: i, model: u, signal: m } = n, O = {
231
- conversationId: s,
229
+ const B = new Y(), ne = async (n, t, s, e, r) => {
230
+ const { onMessage: a, onToken: o, onComplete: c, onError: i, model: u, signal: l } = s, O = {
231
+ conversationId: n,
232
232
  messages: t,
233
233
  model: u,
234
234
  custom_fields: r
@@ -240,17 +240,17 @@ const B = new Y(), se = async (s, t, n, e, r) => {
240
240
  onMessage: (N) => v(N, a, o),
241
241
  onComplete: c,
242
242
  onError: i,
243
- signal: m
243
+ signal: l
244
244
  },
245
245
  e
246
246
  );
247
- }, l = (s) => s instanceof Error && s.message.includes("404"), f = (s) => `/v1/conversations/${E(s)}`;
247
+ }, m = (n) => n instanceof Error && n.message.includes("404"), f = (n) => `/v1/conversations/${E(n)}`;
248
248
  class re {
249
249
  constructor(t) {
250
250
  this.client = t;
251
251
  }
252
- async getConversations(t, n, e) {
253
- const r = `${n ? e ? `${n}/${e}` : `${n}` : ""}`, a = `${d.CONVERSATIONS}/${r}`;
252
+ async getConversations(t, s, e) {
253
+ const r = `${s ? e ? `${s}/${e}` : `${s}` : ""}`, a = `${d.CONVERSATIONS}/${r}`;
254
254
  try {
255
255
  return (await this.client.getRequest(a + "/?limit=1000&recursive=false", t).then((c) => c.items || [])).map((c) => {
256
256
  const { conversationName: i, modelId: u } = j(c);
@@ -264,36 +264,36 @@ class re {
264
264
  };
265
265
  });
266
266
  } catch (o) {
267
- if (l(o))
267
+ if (m(o))
268
268
  return [];
269
269
  throw o;
270
270
  }
271
271
  }
272
- async getConversation(t, n) {
272
+ async getConversation(t, s) {
273
273
  try {
274
274
  return await this.client.getRequest(
275
275
  f(t),
276
- n
276
+ s
277
277
  );
278
278
  } catch (e) {
279
- if (l(e))
279
+ if (m(e))
280
280
  return null;
281
281
  throw e;
282
282
  }
283
283
  }
284
- async getFile(t, n) {
284
+ async getFile(t, s) {
285
285
  try {
286
286
  const e = `${d.VERSION}/${E(t)}`;
287
- return await this.client.getRequest(e, n);
287
+ return await this.client.getRequest(e, s);
288
288
  } catch (e) {
289
- if (l(e))
289
+ if (m(e))
290
290
  return null;
291
291
  throw e;
292
292
  }
293
293
  }
294
- async putOnboardingFile(t, n, e, r) {
294
+ async putOnboardingFile(t, s, e, r) {
295
295
  try {
296
- const a = `${d.VERSION}/${E(n)}`, o = "----NodeMultipartBoundary", i = [
296
+ const a = `${d.VERSION}/${E(s)}`, o = "----NodeMultipartBoundary", i = [
297
297
  `--${o}`,
298
298
  `Content-Disposition: form-data; name="file"; filename="${t}"`,
299
299
  "Content-Type: application/json",
@@ -310,32 +310,42 @@ class re {
310
310
  isFormData: !0
311
311
  });
312
312
  } catch (a) {
313
- if (l(a))
313
+ if (m(a))
314
314
  return null;
315
315
  throw a;
316
316
  }
317
317
  }
318
- async getOnboardingFile(t, n) {
318
+ async getOnboardingFile(t, s) {
319
319
  try {
320
320
  const e = `${d.VERSION}/${E(t)}`;
321
- return await this.client.getRequest(e, n);
321
+ return await this.client.getRequest(e, s);
322
322
  } catch (e) {
323
- if (l(e))
323
+ if (m(e))
324
324
  return null;
325
325
  throw e;
326
326
  }
327
327
  }
328
- async getFileBlob(t, n) {
328
+ async getFileBlob(t, s) {
329
329
  try {
330
330
  const e = `${d.VERSION}/${E(t)}`;
331
- return await this.client.requestBlob(e, n, { method: "GET" });
331
+ return await this.client.requestBlob(e, s, { method: "GET" });
332
332
  } catch (e) {
333
- if (l(e))
333
+ if (m(e))
334
334
  return null;
335
335
  throw e;
336
336
  }
337
337
  }
338
- async createConversation(t, n) {
338
+ async deleteFile(t, s) {
339
+ try {
340
+ const e = `${d.VERSION}/${E(t)}`;
341
+ await this.client.request(e, s, { method: "DELETE" });
342
+ } catch (e) {
343
+ if (m(e))
344
+ return;
345
+ throw e;
346
+ }
347
+ }
348
+ async createConversation(t, s) {
339
349
  const e = t?.id || k(t), { name: r, folderId: a, model: o, messages: c, custom_fields: i } = t, u = {
340
350
  id: e,
341
351
  name: r,
@@ -351,7 +361,7 @@ class re {
351
361
  };
352
362
  return await this.client.request(
353
363
  f(e),
354
- n,
364
+ s,
355
365
  {
356
366
  method: "PUT",
357
367
  body: u
@@ -365,40 +375,40 @@ class re {
365
375
  updatedAt: u.updatedAt
366
376
  };
367
377
  }
368
- async generateConversationLink(t, n) {
378
+ async generateConversationLink(t, s) {
369
379
  return await this.client.postRequest(
370
380
  d.SHARE_CONVERSATION,
371
381
  t,
372
382
  {
373
- body: n
383
+ body: s
374
384
  }
375
385
  );
376
386
  }
377
- async getSharedConversations(t, n) {
387
+ async getSharedConversations(t, s) {
378
388
  return await this.client.postRequest(
379
389
  d.SHARE_CONVERSATION_LIST,
380
390
  t,
381
391
  {
382
- body: n
392
+ body: s
383
393
  }
384
394
  );
385
395
  }
386
- async revokeSharedConversations(t, n) {
396
+ async revokeSharedConversations(t, s) {
387
397
  await this.client.postRequest(
388
398
  d.SHARE_CONVERSATION_REVOKE,
389
399
  t,
390
400
  {
391
- body: n
401
+ body: s
392
402
  }
393
403
  );
394
404
  }
395
- async updateConversation(t, n, e) {
405
+ async updateConversation(t, s, e) {
396
406
  const r = await this.getConversation(t, e);
397
407
  if (!r)
398
408
  throw new Error(`Conversation with id ${t} not found`);
399
409
  const a = {
400
410
  ...r,
401
- ...n,
411
+ ...s,
402
412
  updatedAt: Date.now()
403
413
  };
404
414
  return await this.client.request(
@@ -410,15 +420,15 @@ class re {
410
420
  }
411
421
  );
412
422
  }
413
- async deleteConversation(t, n, e) {
414
- n?.isShared ? await this.client.postRequest(
423
+ async deleteConversation(t, s, e) {
424
+ s?.isShared ? await this.client.postRequest(
415
425
  d.SHARE_CONVERSATION_DISCARD,
416
426
  e,
417
427
  {
418
428
  body: {
419
429
  resources: [
420
430
  {
421
- url: n?.url
431
+ url: s?.url
422
432
  }
423
433
  ]
424
434
  }
@@ -427,7 +437,7 @@ class re {
427
437
  method: "DELETE"
428
438
  });
429
439
  }
430
- async streamChat(t, n) {
440
+ async streamChat(t, s) {
431
441
  const e = t.model.id, r = encodeURIComponent(e), a = `${d.CHAT(r)}?api-version=${this.client.config.version}`, o = {
432
442
  messages: t.messages,
433
443
  stream: !0,
@@ -435,29 +445,29 @@ class re {
435
445
  max_tokens: 4096,
436
446
  custom_fields: t.custom_fields
437
447
  };
438
- return await this.client.stream(a, n, {
448
+ return await this.client.stream(a, s, {
439
449
  method: "POST",
440
450
  body: o,
441
451
  chatReference: t.conversationId
442
452
  });
443
453
  }
444
- async rateResponse(t, n, e, r) {
454
+ async rateResponse(t, s, e, r) {
445
455
  return await this.client.postRequest(
446
456
  d.RATE(t),
447
457
  r,
448
458
  {
449
459
  body: {
450
- responseId: n,
460
+ responseId: s,
451
461
  rate: e
452
462
  }
453
463
  }
454
464
  );
455
465
  }
456
- async renameConversation(t, n, e) {
466
+ async renameConversation(t, s, e) {
457
467
  return await this.client.postRequest(d.RENAME, e, {
458
468
  body: {
459
469
  sourceUrl: t,
460
- destinationUrl: n,
470
+ destinationUrl: s,
461
471
  overwrite: !0
462
472
  }
463
473
  });
@@ -471,16 +481,16 @@ class oe {
471
481
  version: t.version
472
482
  });
473
483
  }
474
- async getRequest(t, n, e) {
475
- return this.request(t, n, { ...e, method: "GET" });
484
+ async getRequest(t, s, e) {
485
+ return this.request(t, s, { ...e, method: "GET" });
476
486
  }
477
- async postRequest(t, n, e) {
478
- return this.request(t, n, { ...e, method: "POST" });
487
+ async postRequest(t, s, e) {
488
+ return this.request(t, s, { ...e, method: "POST" });
479
489
  }
480
- async requestBlob(t, n, e) {
490
+ async requestBlob(t, s, e) {
481
491
  const r = `${this.config.host}${t}`, a = {
482
492
  ..._(this.config.apiKey, {
483
- jwt: n,
493
+ jwt: s,
484
494
  chatReference: e.chatReference
485
495
  }),
486
496
  ...e.headers
@@ -495,10 +505,10 @@ class oe {
495
505
  }), o;
496
506
  }
497
507
  }
498
- async request(t, n, e) {
508
+ async request(t, s, e) {
499
509
  const r = Date.now(), a = `${this.config.host}${t}`, o = {
500
510
  ..._(this.config.apiKey, {
501
- jwt: n,
511
+ jwt: s,
502
512
  chatReference: e.chatReference
503
513
  }),
504
514
  ...e.headers
@@ -507,21 +517,21 @@ class oe {
507
517
  try {
508
518
  const c = await I(a, o, e), i = Date.now() - r;
509
519
  let u;
510
- const m = await c.text();
520
+ const l = await c.text();
511
521
  try {
512
- u = m ? JSON.parse(m) : {};
522
+ u = l ? JSON.parse(l) : {};
513
523
  } catch {
514
524
  if (this.addErrorRequestParsing(
515
525
  a,
516
526
  e,
517
527
  c,
518
528
  i,
519
- m
529
+ l
520
530
  ), !c.ok)
521
531
  throw new Error(
522
- `API request failed: ${c.status} ${c.statusText} - ${m.substring(0, 100)}`
532
+ `API request failed: ${c.status} ${c.statusText} - ${l.substring(0, 100)}`
523
533
  );
524
- u = { data: m };
534
+ u = { data: l };
525
535
  }
526
536
  if (!c.ok) {
527
537
  this.addErrorRequestLog(a, e, c, i, u);
@@ -539,11 +549,11 @@ class oe {
539
549
  }), c;
540
550
  }
541
551
  }
542
- async stream(t, n, e) {
552
+ async stream(t, s, e) {
543
553
  const r = `${this.config.host}${t}`, a = _(
544
554
  this.config.apiKey,
545
555
  {
546
- jwt: n,
556
+ jwt: s,
547
557
  chatReference: e.chatReference
548
558
  },
549
559
  e.headers
@@ -563,17 +573,17 @@ class oe {
563
573
  throw new Error("No response body for stream");
564
574
  return o.body;
565
575
  }
566
- addInfoRequestLog(t, n, e, r) {
576
+ addInfoRequestLog(t, s, e, r) {
567
577
  const a = {
568
578
  method: e.method || "GET",
569
- url: n,
579
+ url: s,
570
580
  headers: U(r)
571
581
  };
572
582
  e.body && (a.body = e.body), console.info(t, a);
573
583
  }
574
- addErrorRequestLog(t, n, e, r, a) {
584
+ addErrorRequestLog(t, s, e, r, a) {
575
585
  console.error("API Request Failed", {
576
- method: n.method,
586
+ method: s.method,
577
587
  url: t,
578
588
  status: e.status,
579
589
  statusText: e.statusText,
@@ -581,9 +591,9 @@ class oe {
581
591
  response: a
582
592
  });
583
593
  }
584
- addErrorRequestParsing(t, n, e, r, a) {
594
+ addErrorRequestParsing(t, s, e, r, a) {
585
595
  console.error("API Response Parse Error", {
586
- method: n.method,
596
+ method: s.method,
587
597
  url: t,
588
598
  status: e.status,
589
599
  statusText: e.statusText,
@@ -608,12 +618,12 @@ export {
608
618
  R as EXCEEDED_LIMIT,
609
619
  W as EXCEEDED_LIMIT_ORDER,
610
620
  $ as InvitationType,
611
- T as ResourceTypes,
621
+ p as ResourceTypes,
612
622
  g as ShareTarget,
613
623
  B as chatStreamSSEClient,
614
624
  ee as decodeApiUrl,
615
625
  E as encodeApiUrl,
616
- ne as formatDateTime,
626
+ se as formatDateTime,
617
627
  k as generateConversationId,
618
628
  D as getErrorMessage,
619
629
  F as getRateLimitRestoreDate,
@@ -623,5 +633,5 @@ export {
623
633
  Q as mergeMessages,
624
634
  j as parseConversationName,
625
635
  I as sendRequest,
626
- se as streamChatResponse
636
+ ne as streamChatResponse
627
637
  };
@@ -17,6 +17,7 @@ export interface CreateConversationRequest {
17
17
  }
18
18
  export interface UpdateConversationRequest {
19
19
  name?: string;
20
+ id?: string;
20
21
  folderId?: string;
21
22
  model?: ModelInfo;
22
23
  prompt?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.3.0-rc.0",
3
+ "version": "0.3.0-rc.10",
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.3.0-rc.0",
17
+ "@epam/statgpt-shared-toolkit": "0.3.0-rc.10",
18
18
  "@epam/ai-dial-shared": "^0.43.3"
19
19
  }
20
20
  }
@@ -6,6 +6,7 @@ export declare enum AttachmentType {
6
6
  JSON = "application/json",
7
7
  JPEG = "image/jpeg",
8
8
  PNG = "image/png",
9
+ CROSS_DATASET_GRID = "cross_dataset_grid",
9
10
  CUSTOM_DATA_GRID = "custom_data_grid",
10
11
  CUSTOM_CHART = "custom_chart",
11
12
  CUSTOM_CODE_SAMPLE = "custom_code_sample"