@epam/statgpt-dial-toolkit 0.1.0-rc.0 → 0.1.0-rc.2

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