@epam/statgpt-dial-toolkit 0.2.0-rc.41 → 0.2.0-rc.43

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.
@@ -6,6 +6,7 @@ export declare const DIAL_API_ROUTES: {
6
6
  readonly CHAT: (modelId: string) => string;
7
7
  readonly MODELS: "/openai/models";
8
8
  readonly CONFIGURATION: (modelId: string) => string;
9
+ readonly DATASETS_METADATA: (deploymentId: string) => string;
9
10
  readonly SHARE_CONVERSATION: "/v1/ops/resource/share/create";
10
11
  readonly SHARE_CONVERSATION_ACCEPT: (invitationId: string) => string;
11
12
  readonly SHARE_CONVERSATION_DETAILS: (invitationId: string) => string;
package/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",R=`/${l}/ops/resource/share`,u={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`,SHARE_CONVERSATION:`${R}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${l}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${l}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:n=>`/${l}/${n}/rate`,RENAME:`/${l}/ops/resource/move`},x={CONTENT_FILTER:"content_filter"};var g=(n=>(n.CONVERSATION="CONVERSATION",n))(g||{}),I=(n=>(n.ME="me",n.OTHERS="others",n))(I||{}),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))(y||{}),T=(n=>(n.LINK="link",n))(T||{});const D=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),N=(n,t,s)=>{if(t?.(n),s){const e=D(n);e&&s(e)}},$=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,H=(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)},L=(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&&V(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=H(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 V(n,t){if(t.content){const s=U(t.content);s!=null?n.content=n.content.slice(0,-s):n.content=`${n.content||""}${t.content}`}}function U(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const M={CHAT:"/api/chat"},j="application/json",k="Content-Type",p="Api-Key",F="X-CONVERSATION-ID",_="Ocp-Apim-Subscription-Key";class O 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=n=>n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," ")||"",A=(n,t,s)=>{const e={[k]:t?.contentType||j};return t?.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[p]=n),t?.chatReference&&(e[F]=t.chatReference),{...e,...s}},B=n=>{const t={...n};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[_]&&(t[_]=t[_].substring(0,8)+"...[REDACTED]"),t},J=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),v=n=>{const t=n.name?.split("__")||[],s=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:s}},w=n=>{const t=Date.now(),s=K(n.name);return`${n.folderId}/${s}-${t}`},z=n=>({resourceTypes:[g.CONVERSATION],with:n}),f=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 E(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function G(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}class b{constructor(){this.decoder=new TextDecoder}async streamChat(t,s,e={},r){const{onMessage:a,onError:o,onComplete:c,signal:i}=e;try{const d=await this.initializeStreamRequest(t,s,i,r);await this.processStreamData(d,a),c?.()}catch(d){this.handleStreamError(d,o)}}async initializeStreamRequest(t,s,e,r){const a=A(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:s,signal:e});if(!o.ok){const c=await o.text();let i={};try{i=JSON.parse(c)}catch{i.error="Failed to parse error body"}throw new O({status:o.status,message:i.error??"No response body"})}if(!o.body)throw new O({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 c=e.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",R=`/${l}/ops/resource/share`,u={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:`${R}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${l}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${l}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:n=>`/${l}/${n}/rate`,RENAME:`/${l}/ops/resource/move`},D={CONTENT_FILTER:"content_filter"};var g=(n=>(n.CONVERSATION="CONVERSATION",n))(g||{}),T=(n=>(n.ME="me",n.OTHERS="others",n))(T||{}),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))(y||{}),I=(n=>(n.LINK="link",n))(I||{});const x=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),N=(n,t,s)=>{if(t?.(n),s){const e=x(n);e&&s(e)}},$=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,H=(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)},L=(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&&V(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=H(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 V(n,t){if(t.content){const s=U(t.content);s!=null?n.content=n.content.slice(0,-s):n.content=`${n.content||""}${t.content}`}}function U(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const M={CHAT:"/api/chat"},j="application/json",k="Content-Type",p="Api-Key",F="X-CONVERSATION-ID",_="Ocp-Apim-Subscription-Key";class O 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=n=>n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," ")||"",A=(n,t,s)=>{const e={[k]:t?.contentType||j};return t?.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[p]=n),t?.chatReference&&(e[F]=t.chatReference),{...e,...s}},B=n=>{const t={...n};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[_]&&(t[_]=t[_].substring(0,8)+"...[REDACTED]"),t},J=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),v=n=>{const t=n.name?.split("__")||[],s=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:s}},w=n=>{const t=Date.now(),s=K(n.name);return`${n.folderId}/${s}-${t}`},z=n=>({resourceTypes:[g.CONVERSATION],with:n}),f=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 E(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function G(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}class b{constructor(){this.decoder=new TextDecoder}async streamChat(t,s,e={},r){const{onMessage:a,onError:o,onComplete:c,signal:i}=e;try{const d=await this.initializeStreamRequest(t,s,i,r);await this.processStreamData(d,a),c?.()}catch(d){this.handleStreamError(d,o)}}async initializeStreamRequest(t,s,e,r){const a=A(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:s,signal:e});if(!o.ok){const c=await o.text();let i={};try{i=JSON.parse(c)}catch{i.error="Failed to parse error body"}throw new O({status:o.status,message:i.error??"No response body"})}if(!o.body)throw new O({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 c=e.split(`
2
2
  `);e=c.pop()||"";for(const i of c)this.parseSSEDataLine(i,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 q=new b,Y=async(n,t,s,e,r)=>{const{onMessage:a,onToken:o,onComplete:c,onError:i,model:d,signal:m}=s,C={conversationId:n,messages:t,model:d,custom_fields:r};await q.streamChat(M.CHAT,C,{onMessage:P=>N(P,a,o),onComplete:c,onError:i,signal:m},e)},h=n=>n instanceof Error&&n.message.includes("404"),S=n=>`/v1/conversations/${E(n)}`;class W{constructor(t){this.client=t}async getConversations(t,s,e){const r=`${s?e?`${s}/${e}`:`${s}`:""}`,a=`${u.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(c=>c.items||[])).map(c=>{const{conversationName:i,modelId:d}=v(c);return{id:c.url?.replace("conversations/","")||c.name,name:i,folderId:r,createdAt:c.createdAt,updatedAt:c.updatedAt,model:{id:d,name:d}}})}catch(o){if(h(o))return[];throw o}}async getConversation(t,s){try{return await this.client.getRequest(S(t),s)}catch(e){if(h(e))return null;throw e}}async getFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async putOnboardingFile(t,s,e,r){try{const a=`${u.VERSION}/${E(s)}`,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(a,r,{method:"PUT",body:i,headers:J(o),isFormData:!0})}catch(a){if(h(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,s){const e=t?.id||w(t),{name:r,folderId:a,model:o,messages:c,custom_fields:i}=t,d={id:e,name:r,folderId:a,model:o,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:i};return await this.client.request(S(e),s,{method:"PUT",body:d}),{id:e,name:r,folderId:a,model:o,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(u.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(S(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${u.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(u.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,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,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 f(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 c=await f(a,o,e),i=Date.now()-r;let d;const m=await c.text();try{d=m?JSON.parse(m):{}}catch{if(this.addErrorRequestParsing(a,e,c,i,m),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${m.substring(0,100)}`);d={data:m}}if(!c.ok){this.addErrorRequestLog(a,e,c,i,d);const C=$(d,c);throw new Error(`API request failed: ${C}`)}return d}catch(c){const i=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${i}ms`,error:c instanceof Error?c.message:String(c)}),c}}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 f(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:B(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.ChatStreamSSEClient=b;exports.ConversationApi=W;exports.DIAL_API_ROUTES=u;exports.DIAL_ERROR_CODES=x;exports.DialApiClient=X;exports.InvitationType=T;exports.ResourceTypes=g;exports.ShareTarget=I;exports.chatStreamSSEClient=q;exports.decodeApiUrl=G;exports.encodeApiUrl=E;exports.generateConversationId=w;exports.getErrorMessage=$;exports.getSharedConversationsRequest=z;exports.handleStreamMessage=N;exports.mergeMessages=L;exports.parseConversationName=v;exports.sendRequest=f;exports.streamChatResponse=Y;
3
+ `);return await this.client.request(a,r,{method:"PUT",body:i,headers:J(o),isFormData:!0})}catch(a){if(h(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,s){const e=t?.id||w(t),{name:r,folderId:a,model:o,messages:c,custom_fields:i}=t,d={id:e,name:r,folderId:a,model:o,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:i};return await this.client.request(S(e),s,{method:"PUT",body:d}),{id:e,name:r,folderId:a,model:o,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(u.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(S(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${u.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(u.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,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,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 f(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 c=await f(a,o,e),i=Date.now()-r;let d;const m=await c.text();try{d=m?JSON.parse(m):{}}catch{if(this.addErrorRequestParsing(a,e,c,i,m),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${m.substring(0,100)}`);d={data:m}}if(!c.ok){this.addErrorRequestLog(a,e,c,i,d);const C=$(d,c);throw new Error(`API request failed: ${C}`)}return d}catch(c){const i=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${i}ms`,error:c instanceof Error?c.message:String(c)}),c}}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 f(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:B(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.ChatStreamSSEClient=b;exports.ConversationApi=W;exports.DIAL_API_ROUTES=u;exports.DIAL_ERROR_CODES=D;exports.DialApiClient=X;exports.InvitationType=I;exports.ResourceTypes=g;exports.ShareTarget=T;exports.chatStreamSSEClient=q;exports.decodeApiUrl=G;exports.encodeApiUrl=E;exports.generateConversationId=w;exports.getErrorMessage=$;exports.getSharedConversationsRequest=z;exports.handleStreamMessage=N;exports.mergeMessages=L;exports.parseConversationName=v;exports.sendRequest=f;exports.streamChatResponse=Y;
package/index.mjs CHANGED
@@ -6,6 +6,7 @@ const E = "/v1/ops/resource/share", u = {
6
6
  CHAT: (n) => `/openai/deployments/${n}/chat/completions`,
7
7
  MODELS: "/openai/models",
8
8
  CONFIGURATION: (n) => `/v1/deployments/${n}/configuration`,
9
+ DATASETS_METADATA: (n) => `/v1/deployments/${n}/route/metadata/datasets`,
9
10
  SHARE_CONVERSATION: `${E}/create`,
10
11
  SHARE_CONVERSATION_ACCEPT: (n) => `/v1/invitations/${n}?accept=true`,
11
12
  SHARE_CONVERSATION_DETAILS: (n) => `/v1/invitations/${n}`,
@@ -17,12 +18,12 @@ const E = "/v1/ops/resource/share", u = {
17
18
  }, K = {
18
19
  CONTENT_FILTER: "content_filter"
19
20
  };
20
- var N = /* @__PURE__ */ ((n) => (n.CONVERSATION = "CONVERSATION", n))(N || {}), C = /* @__PURE__ */ ((n) => (n.ME = "me", n.OTHERS = "others", n))(C || {}), g = /* @__PURE__ */ ((n) => (n.CSV = "text/csv", n.TABLE = "application/dial-ttyd-table", n.PLOTLY = "application/vnd.plotly.v1+json", n.MARKDOWN = "text/markdown", n.JSON = "application/json", n.JPEG = "image/jpeg", n.PNG = "image/png", n.CUSTOM_DATA_GRID = "custom_data_grid", n.CUSTOM_CHART = "custom_chart", n))(g || {}), y = /* @__PURE__ */ ((n) => (n.LINK = "link", n))(y || {});
21
- const T = (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(
21
+ var _ = /* @__PURE__ */ ((n) => (n.CONVERSATION = "CONVERSATION", n))(_ || {}), C = /* @__PURE__ */ ((n) => (n.ME = "me", n.OTHERS = "others", n))(C || {}), T = /* @__PURE__ */ ((n) => (n.CSV = "text/csv", n.TABLE = "application/dial-ttyd-table", n.PLOTLY = "application/vnd.plotly.v1+json", n.MARKDOWN = "text/markdown", n.JSON = "application/json", n.JPEG = "image/jpeg", n.PNG = "image/png", n.CUSTOM_DATA_GRID = "custom_data_grid", n.CUSTOM_CHART = "custom_chart", n))(T || {}), g = /* @__PURE__ */ ((n) => (n.LINK = "link", n))(g || {});
22
+ const y = (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(
22
23
  `Using complete message format: ${n.choices[0].message.content}`
23
24
  ), n.choices[0].message.content) : (console.info("Unknown SSE data format:", n), null), $ = (n, t, s) => {
24
25
  if (t?.(n), s) {
25
- const e = T(n);
26
+ const e = y(n);
26
27
  e && s(e);
27
28
  }
28
29
  }, v = (n, t) => n.error || n.message || `${t.status} ${t.statusText}`, w = (n, t) => {
@@ -78,7 +79,7 @@ const D = (n) => n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|
78
79
  }, j = (n) => {
79
80
  const t = Date.now(), s = D(n.name);
80
81
  return `${n.folderId}/${s}-${t}`;
81
- }, J = (n) => ({ resourceTypes: [N.CONVERSATION], with: n }), p = async (n, t, s) => await fetch(n, {
82
+ }, J = (n) => ({ resourceTypes: [_.CONVERSATION], with: n }), p = async (n, t, s) => await fetch(n, {
82
83
  method: s.method || "GET",
83
84
  headers: t,
84
85
  body: s?.isFormData && typeof s?.body == "string" ? s.body : JSON.stringify(s.body),
@@ -187,7 +188,7 @@ class k {
187
188
  }
188
189
  }
189
190
  const F = new k(), G = async (n, t, s, e, r) => {
190
- const { onMessage: a, onToken: o, onComplete: c, onError: i, model: d, signal: l } = s, O = {
191
+ const { onMessage: a, onToken: o, onComplete: c, onError: i, model: d, signal: m } = s, O = {
191
192
  conversationId: n,
192
193
  messages: t,
193
194
  model: d,
@@ -197,14 +198,14 @@ const F = new k(), G = async (n, t, s, e, r) => {
197
198
  V.CHAT,
198
199
  O,
199
200
  {
200
- onMessage: (_) => $(_, a, o),
201
+ onMessage: (N) => $(N, a, o),
201
202
  onComplete: c,
202
203
  onError: i,
203
- signal: l
204
+ signal: m
204
205
  },
205
206
  e
206
207
  );
207
- }, m = (n) => n instanceof Error && n.message.includes("404"), R = (n) => `/v1/conversations/${h(n)}`;
208
+ }, l = (n) => n instanceof Error && n.message.includes("404"), R = (n) => `/v1/conversations/${h(n)}`;
208
209
  class Y {
209
210
  constructor(t) {
210
211
  this.client = t;
@@ -224,7 +225,7 @@ class Y {
224
225
  };
225
226
  });
226
227
  } catch (o) {
227
- if (m(o))
228
+ if (l(o))
228
229
  return [];
229
230
  throw o;
230
231
  }
@@ -236,7 +237,7 @@ class Y {
236
237
  s
237
238
  );
238
239
  } catch (e) {
239
- if (m(e))
240
+ if (l(e))
240
241
  return null;
241
242
  throw e;
242
243
  }
@@ -246,7 +247,7 @@ class Y {
246
247
  const e = `${u.VERSION}/${h(t)}`;
247
248
  return await this.client.getRequest(e, s);
248
249
  } catch (e) {
249
- if (m(e))
250
+ if (l(e))
250
251
  return null;
251
252
  throw e;
252
253
  }
@@ -270,7 +271,7 @@ class Y {
270
271
  isFormData: !0
271
272
  });
272
273
  } catch (a) {
273
- if (m(a))
274
+ if (l(a))
274
275
  return null;
275
276
  throw a;
276
277
  }
@@ -280,7 +281,7 @@ class Y {
280
281
  const e = `${u.VERSION}/${h(t)}`;
281
282
  return await this.client.getRequest(e, s);
282
283
  } catch (e) {
283
- if (m(e))
284
+ if (l(e))
284
285
  return null;
285
286
  throw e;
286
287
  }
@@ -290,7 +291,7 @@ class Y {
290
291
  const e = `${u.VERSION}/${h(t)}`;
291
292
  return await this.client.requestBlob(e, s, { method: "GET" });
292
293
  } catch (e) {
293
- if (m(e))
294
+ if (l(e))
294
295
  return null;
295
296
  throw e;
296
297
  }
@@ -467,21 +468,21 @@ class W {
467
468
  try {
468
469
  const c = await p(a, o, e), i = Date.now() - r;
469
470
  let d;
470
- const l = await c.text();
471
+ const m = await c.text();
471
472
  try {
472
- d = l ? JSON.parse(l) : {};
473
+ d = m ? JSON.parse(m) : {};
473
474
  } catch {
474
475
  if (this.addErrorRequestParsing(
475
476
  a,
476
477
  e,
477
478
  c,
478
479
  i,
479
- l
480
+ m
480
481
  ), !c.ok)
481
482
  throw new Error(
482
- `API request failed: ${c.status} ${c.statusText} - ${l.substring(0, 100)}`
483
+ `API request failed: ${c.status} ${c.statusText} - ${m.substring(0, 100)}`
483
484
  );
484
- d = { data: l };
485
+ d = { data: m };
485
486
  }
486
487
  if (!c.ok) {
487
488
  this.addErrorRequestLog(a, e, c, i, d);
@@ -555,14 +556,14 @@ class W {
555
556
  }
556
557
  }
557
558
  export {
558
- g as AttachmentType,
559
+ T as AttachmentType,
559
560
  k as ChatStreamSSEClient,
560
561
  Y as ConversationApi,
561
562
  u as DIAL_API_ROUTES,
562
563
  K as DIAL_ERROR_CODES,
563
564
  W as DialApiClient,
564
- y as InvitationType,
565
- N as ResourceTypes,
565
+ g as InvitationType,
566
+ _ as ResourceTypes,
566
567
  C as ShareTarget,
567
568
  F as chatStreamSSEClient,
568
569
  z as decodeApiUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@epam/statgpt-dial-toolkit",
3
- "version": "0.2.0-rc.41",
3
+ "version": "0.2.0-rc.43",
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.41",
17
+ "@epam/statgpt-shared-toolkit": "0.2.0-rc.43",
18
18
  "@epam/ai-dial-shared": "^0.34.0"
19
19
  }
20
20
  }