@epam/statgpt-dial-toolkit 0.2.0-rc.30 → 0.2.0-rc.31

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