@epam/statgpt-dial-toolkit 0.2.0-rc.44 → 0.2.0-rc.46
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.
- package/index.cjs +3 -3
- package/index.mjs +87 -87
- package/package.json +2 -2
- package/types/attachment-type.d.ts +2 -1
package/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",R=`/${l}/ops/resource/share`,u={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:n=>`/${l}/metadata/conversations/${n}`,CHAT:n=>`/openai/deployments/${n}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:n=>`/${l}/deployments/${n}/configuration`,DATASETS_METADATA:n=>`/v1/deployments/${n}/route/metadata/datasets`,SHARE_CONVERSATION:`${R}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${l}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${l}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:n=>`/${l}/${n}/rate`,RENAME:`/${l}/ops/resource/move`},D={CONTENT_FILTER:"content_filter"};var
|
|
2
|
-
`);e=c.pop()||"";for(const i of c)this.parseSSEDataLine(i,s)}}finally{t.releaseLock()}}handleStreamError(t,s){const e=t instanceof Error?t:new Error(String(t));throw s?.(e),e}parseSSEDataLine(t,s){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let a;try{a=JSON.parse(r)}catch(o){console.error(`Failed to parse SSE data: ${r} ${o}`)}s?.(a)}}}const q=new b,Y=async(n,t,s,e,r)=>{const{onMessage:a,onToken:o,onComplete:c,onError:i,model:d,signal:m}=s,C={conversationId:n,messages:t,model:d,custom_fields:r};await q.streamChat(
|
|
3
|
-
`);return await this.client.request(a,r,{method:"PUT",body:i,headers:J(o),isFormData:!0})}catch(a){if(h(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,s){const e=t?.id||w(t),{name:r,folderId:a,model:o,messages:c,custom_fields:i}=t,d={id:e,name:r,folderId:a,model:o,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:i};return await this.client.request(S(e),s,{method:"PUT",body:d}),{id:e,name:r,folderId:a,model:o,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(u.SHARE_CONVERSATION_REVOKE,t,{body:s})}async updateConversation(t,s,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...s,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${u.CHAT(r)}?api-version=${this.client.config.version}`,o={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(a,s,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,s,e,r){return await this.client.postRequest(u.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,overwrite:!0}})}}class X{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,s,e){return this.request(t,s,{...e,method:"GET"})}async postRequest(t,s,e){return this.request(t,s,{...e,method:"POST"})}async requestBlob(t,s,e){const r=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};try{return(await f(r,a,e)).blob()}catch(o){throw console.error("API Request Exception",{method:e.method,url:r,error:o instanceof Error?o.message:String(o)}),o}}async request(t,s,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const c=await f(a,o,e),i=Date.now()-r;let d;const m=await c.text();try{d=m?JSON.parse(m):{}}catch{if(this.addErrorRequestParsing(a,e,c,i,m),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${m.substring(0,100)}`);d={data:m}}if(!c.ok){this.addErrorRequestLog(a,e,c,i,d);const C=$(d,c);throw new Error(`API request failed: ${C}`)}return d}catch(c){const i=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${i}ms`,error:c instanceof Error?c.message:String(c)}),c}}async stream(t,s,e){const r=`${this.config.host}${t}`,a=A(this.config.apiKey,{jwt:s,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",r,e,a);const o=await f(r,a,e);if(!o.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,status:o.status,statusText:o.statusText}),new Error(`Stream request failed: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("No response body for stream");return o.body}addInfoRequestLog(t,s,e,r){const a={method:e.method||"GET",url:s,headers:B(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,s,e,r,a){console.error("API Request Failed",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,s,e,r,a){console.error("API Response Parse Error",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",R=`/${l}/ops/resource/share`,u={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:n=>`/${l}/metadata/conversations/${n}`,CHAT:n=>`/openai/deployments/${n}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:n=>`/${l}/deployments/${n}/configuration`,DATASETS_METADATA:n=>`/v1/deployments/${n}/route/metadata/datasets`,SHARE_CONVERSATION:`${R}/create`,SHARE_CONVERSATION_ACCEPT:n=>`/${l}/invitations/${n}?accept=true`,SHARE_CONVERSATION_DETAILS:n=>`/${l}/invitations/${n}`,SHARE_CONVERSATION_LIST:`${R}/list`,SHARE_CONVERSATION_DISCARD:`${R}/discard`,SHARE_CONVERSATION_REVOKE:`${R}/revoke`,RATE:n=>`/${l}/${n}/rate`,RENAME:`/${l}/ops/resource/move`},D={CONTENT_FILTER:"content_filter"};var O=(n=>(n.CONVERSATION="CONVERSATION",n))(O||{}),T=(n=>(n.ME="me",n.OTHERS="others",n))(T||{}),I=(n=>(n.CSV="text/csv",n.TABLE="application/dial-ttyd-table",n.PLOTLY="application/vnd.plotly.v1+json",n.MARKDOWN="text/markdown",n.JSON="application/json",n.JPEG="image/jpeg",n.PNG="image/png",n.CUSTOM_DATA_GRID="custom_data_grid",n.CUSTOM_CHART="custom_chart",n.CUSTOM_CODE_SAMPLE="custom_code_sample",n))(I||{}),y=(n=>(n.LINK="link",n))(y||{});const x=n=>n.content?(console.info(`Using direct content format: ${n.content}`),n.content):n.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`),n.choices[0].delta.content):n.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${n.choices[0].message.content}`),n.choices[0].message.content):(console.info("Unknown SSE data format:",n),null),N=(n,t,s)=>{if(t?.(n),s){const e=x(n);e&&s(e)}},$=(n,t)=>n.error||n.message||`${t.status} ${t.statusText}`,H=(n,t)=>{const s=n?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{s[e.index]?(e.attachments&&(s[e.index].attachments=(s[e.index].attachments||[]).concat(e.attachments)),e.content&&(s[e.index].content=(s[e.index].content||"")+e.content),e.name&&(s[e.index].name=(s[e.index].name||"")+e.name),e.status&&(s[e.index].status=e.status)):s[e.index]=e}),Object.values(s)},L=(n,t)=>{const s=structuredClone(n);return t.forEach(e=>{e.errorMessage&&(s.errorMessage=e.errorMessage),e.role&&(s.role=e.role),e.responseId&&(s.responseId=e.responseId),e.content&&V(s,e),e.custom_content&&(s.custom_content||(s.custom_content={}),e.custom_content.attachments&&(s.custom_content.attachments||(s.custom_content.attachments=[]),s.custom_content.attachments=s.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(s.custom_content.stages||(s.custom_content.stages=[]),s.custom_content.stages=H(s.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(s.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(s.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(s.custom_content.form_value=e.custom_content.form_value))}),s};function V(n,t){if(t.content){const s=M(t.content);s!=null?n.content=n.content.slice(0,-s):n.content=`${n.content||""}${t.content}`}}function M(n){const t=n.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const U={CHAT:"/api/chat"},j="application/json",k="Content-Type",p="Api-Key",F="X-CONVERSATION-ID",_="Ocp-Apim-Subscription-Key";class g extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details}}const K=n=>n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").replace(/-/g," ")||"",A=(n,t,s)=>{const e={[k]:t?.contentType||j};return t?.jwt?e.Authorization=`Bearer ${t.jwt}`:n&&(e[p]=n),t?.chatReference&&(e[F]=t.chatReference),{...e,...s}},B=n=>{const t={...n};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[_]&&(t[_]=t[_].substring(0,8)+"...[REDACTED]"),t},J=n=>({"Content-Type":`multipart/form-data; boundary=${n}`}),v=n=>{const t=n.name?.split("__")||[],s=t.length>1?t.slice(1).join("__"):n.name;return{modelId:t[0],conversationName:s}},w=n=>{const t=Date.now(),s=K(n.name);return`${n.folderId}/${s}-${t}`},z=n=>({resourceTypes:[O.CONVERSATION],with:n}),f=async(n,t,s)=>await fetch(n,{method:s.method||"GET",headers:t,body:s?.isFormData&&typeof s?.body=="string"?s.body:JSON.stringify(s.body),signal:s?.signal});function E(n){return n.split("/").map(t=>encodeURIComponent(t)).join("/")}function G(n){return n.split("/").map(t=>decodeURIComponent(t)).join("/")}class b{constructor(){this.decoder=new TextDecoder}async streamChat(t,s,e={},r){const{onMessage:a,onError:o,onComplete:c,signal:i}=e;try{const d=await this.initializeStreamRequest(t,s,i,r);await this.processStreamData(d,a),c?.()}catch(d){this.handleStreamError(d,o)}}async initializeStreamRequest(t,s,e,r){const a=A(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:s,signal:e});if(!o.ok){const c=await o.text();let i={};try{i=JSON.parse(c)}catch{i.error="Failed to parse error body"}throw new g({status:o.status,message:i.error??"No response body"})}if(!o.body)throw new g({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,s){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,s);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const c=e.split(`
|
|
2
|
+
`);e=c.pop()||"";for(const i of c)this.parseSSEDataLine(i,s)}}finally{t.releaseLock()}}handleStreamError(t,s){const e=t instanceof Error?t:new Error(String(t));throw s?.(e),e}parseSSEDataLine(t,s){const e=t.trim();if(!(!e||e.startsWith(":"))&&e.startsWith("data: ")){const r=e.slice(6);if(r==="[DONE]"){console.info("SSE: Stream completed");return}let a;try{a=JSON.parse(r)}catch(o){console.error(`Failed to parse SSE data: ${r} ${o}`)}s?.(a)}}}const q=new b,Y=async(n,t,s,e,r)=>{const{onMessage:a,onToken:o,onComplete:c,onError:i,model:d,signal:m}=s,C={conversationId:n,messages:t,model:d,custom_fields:r};await q.streamChat(U.CHAT,C,{onMessage:P=>N(P,a,o),onComplete:c,onError:i,signal:m},e)},h=n=>n instanceof Error&&n.message.includes("404"),S=n=>`/v1/conversations/${E(n)}`;class W{constructor(t){this.client=t}async getConversations(t,s,e){const r=`${s?e?`${s}/${e}`:`${s}`:""}`,a=`${u.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(c=>c.items||[])).map(c=>{const{conversationName:i,modelId:d}=v(c);return{id:c.url?.replace("conversations/","")||c.name,name:i,folderId:r,createdAt:c.createdAt,updatedAt:c.updatedAt,model:{id:d,name:d}}})}catch(o){if(h(o))return[];throw o}}async getConversation(t,s){try{return await this.client.getRequest(S(t),s)}catch(e){if(h(e))return null;throw e}}async getFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async putOnboardingFile(t,s,e,r){try{const a=`${u.VERSION}/${E(s)}`,o="----NodeMultipartBoundary",i=[`--${o}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${o}--`,""].join(`\r
|
|
3
|
+
`);return await this.client.request(a,r,{method:"PUT",body:i,headers:J(o),isFormData:!0})}catch(a){if(h(a))return null;throw a}}async getOnboardingFile(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.getRequest(e,s)}catch(e){if(h(e))return null;throw e}}async getFileBlob(t,s){try{const e=`${u.VERSION}/${E(t)}`;return await this.client.requestBlob(e,s,{method:"GET"})}catch(e){if(h(e))return null;throw e}}async createConversation(t,s){const e=t?.id||w(t),{name:r,folderId:a,model:o,messages:c,custom_fields:i}=t,d={id:e,name:r,folderId:a,model:o,messages:c||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:i};return await this.client.request(S(e),s,{method:"PUT",body:d}),{id:e,name:r,folderId:a,model:o,createdAt:d.createdAt,updatedAt:d.updatedAt}}async generateConversationLink(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION,t,{body:s})}async getSharedConversations(t,s){return await this.client.postRequest(u.SHARE_CONVERSATION_LIST,t,{body:s})}async revokeSharedConversations(t,s){await this.client.postRequest(u.SHARE_CONVERSATION_REVOKE,t,{body:s})}async updateConversation(t,s,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...s,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:a})}async deleteConversation(t,s,e){s?.isShared?await this.client.postRequest(u.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:s?.url}]}}):await this.client.request(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,s){const e=t.model.id,r=encodeURIComponent(e),a=`${u.CHAT(r)}?api-version=${this.client.config.version}`,o={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(a,s,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,s,e,r){return await this.client.postRequest(u.RATE(t),r,{body:{responseId:s,rate:e}})}async renameConversation(t,s,e){return await this.client.postRequest(u.RENAME,e,{body:{sourceUrl:t,destinationUrl:s,overwrite:!0}})}}class X{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,s,e){return this.request(t,s,{...e,method:"GET"})}async postRequest(t,s,e){return this.request(t,s,{...e,method:"POST"})}async requestBlob(t,s,e){const r=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};try{return(await f(r,a,e)).blob()}catch(o){throw console.error("API Request Exception",{method:e.method,url:r,error:o instanceof Error?o.message:String(o)}),o}}async request(t,s,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...A(this.config.apiKey,{jwt:s,chatReference:e.chatReference}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const c=await f(a,o,e),i=Date.now()-r;let d;const m=await c.text();try{d=m?JSON.parse(m):{}}catch{if(this.addErrorRequestParsing(a,e,c,i,m),!c.ok)throw new Error(`API request failed: ${c.status} ${c.statusText} - ${m.substring(0,100)}`);d={data:m}}if(!c.ok){this.addErrorRequestLog(a,e,c,i,d);const C=$(d,c);throw new Error(`API request failed: ${C}`)}return d}catch(c){const i=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${i}ms`,error:c instanceof Error?c.message:String(c)}),c}}async stream(t,s,e){const r=`${this.config.host}${t}`,a=A(this.config.apiKey,{jwt:s,chatReference:e.chatReference},e.headers);this.addInfoRequestLog("Stream Request",r,e,a);const o=await f(r,a,e);if(!o.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,status:o.status,statusText:o.statusText}),new Error(`Stream request failed: ${o.status} ${o.statusText}`);if(!o.body)throw new Error("No response body for stream");return o.body}addInfoRequestLog(t,s,e,r){const a={method:e.method||"GET",url:s,headers:B(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,s,e,r,a){console.error("API Request Failed",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,s,e,r,a){console.error("API Response Parse Error",{method:s.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=I;exports.ChatStreamSSEClient=b;exports.ConversationApi=W;exports.DIAL_API_ROUTES=u;exports.DIAL_ERROR_CODES=D;exports.DialApiClient=X;exports.InvitationType=y;exports.ResourceTypes=O;exports.ShareTarget=T;exports.chatStreamSSEClient=q;exports.decodeApiUrl=G;exports.encodeApiUrl=E;exports.generateConversationId=w;exports.getErrorMessage=$;exports.getSharedConversationsRequest=z;exports.handleStreamMessage=N;exports.mergeMessages=L;exports.parseConversationName=v;exports.sendRequest=f;exports.streamChatResponse=Y;
|
package/index.mjs
CHANGED
|
@@ -18,7 +18,7 @@ const E = "/v1/ops/resource/share", u = {
|
|
|
18
18
|
}, K = {
|
|
19
19
|
CONTENT_FILTER: "content_filter"
|
|
20
20
|
};
|
|
21
|
-
var
|
|
21
|
+
var I = /* @__PURE__ */ ((n) => (n.CONVERSATION = "CONVERSATION", n))(I || {}), N = /* @__PURE__ */ ((n) => (n.ME = "me", n.OTHERS = "others", n))(N || {}), T = /* @__PURE__ */ ((n) => (n.CSV = "text/csv", n.TABLE = "application/dial-ttyd-table", n.PLOTLY = "application/vnd.plotly.v1+json", n.MARKDOWN = "text/markdown", n.JSON = "application/json", n.JPEG = "image/jpeg", n.PNG = "image/png", n.CUSTOM_DATA_GRID = "custom_data_grid", n.CUSTOM_CHART = "custom_chart", n.CUSTOM_CODE_SAMPLE = "custom_code_sample", n))(T || {}), g = /* @__PURE__ */ ((n) => (n.LINK = "link", n))(g || {});
|
|
22
22
|
const y = (n) => n.content ? (console.info(`Using direct content format: ${n.content}`), n.content) : n.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${n.choices[0].delta.content}`), n.choices[0].delta.content) : n.choices?.[0]?.message?.content ? (console.info(
|
|
23
23
|
`Using complete message format: ${n.choices[0].message.content}`
|
|
24
24
|
), n.choices[0].message.content) : (console.info("Unknown SSE data format:", n), null), $ = (n, t, s) => {
|
|
@@ -28,7 +28,7 @@ const y = (n) => n.content ? (console.info(`Using direct content format: ${n.con
|
|
|
28
28
|
}
|
|
29
29
|
}, v = (n, t) => n.error || n.message || `${t.status} ${t.statusText}`, w = (n, t) => {
|
|
30
30
|
const s = n?.reduce(
|
|
31
|
-
(e,
|
|
31
|
+
(e, o) => (e[o.index] = o, e),
|
|
32
32
|
{}
|
|
33
33
|
);
|
|
34
34
|
return t.forEach((e) => {
|
|
@@ -57,17 +57,17 @@ function q(n) {
|
|
|
57
57
|
}
|
|
58
58
|
const V = {
|
|
59
59
|
CHAT: "/api/chat"
|
|
60
|
-
}, x = "application/json", P = "Content-Type", f = "Api-Key",
|
|
61
|
-
class
|
|
60
|
+
}, x = "application/json", P = "Content-Type", f = "Api-Key", D = "X-CONVERSATION-ID", A = "Ocp-Apim-Subscription-Key";
|
|
61
|
+
class _ extends Error {
|
|
62
62
|
constructor(t) {
|
|
63
63
|
super(t.message), this.isHttpError = !0, this.name = "HttpError", this.code = t.code, this.status = t.status, this.details = t.details;
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
-
const
|
|
66
|
+
const H = (n) => n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").replace(/-/g, " ") || "", S = (n, t, s) => {
|
|
67
67
|
const e = {
|
|
68
68
|
[P]: t?.contentType || x
|
|
69
69
|
};
|
|
70
|
-
return t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : n && (e[f] = n), t?.chatReference && (e[
|
|
70
|
+
return t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : n && (e[f] = n), t?.chatReference && (e[D] = t.chatReference), { ...e, ...s };
|
|
71
71
|
}, L = (n) => {
|
|
72
72
|
const t = { ...n };
|
|
73
73
|
return t[f] && (t[f] = t[f].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[A] && (t[A] = t[A].substring(0, 8) + "...[REDACTED]"), t;
|
|
@@ -77,9 +77,9 @@ const D = (n) => n?.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|
|
|
|
77
77
|
const t = n.name?.split("__") || [], s = t.length > 1 ? t.slice(1).join("__") : n.name;
|
|
78
78
|
return { modelId: t[0], conversationName: s };
|
|
79
79
|
}, j = (n) => {
|
|
80
|
-
const t = Date.now(), s =
|
|
80
|
+
const t = Date.now(), s = H(n.name);
|
|
81
81
|
return `${n.folderId}/${s}-${t}`;
|
|
82
|
-
}, J = (n) => ({ resourceTypes: [
|
|
82
|
+
}, J = (n) => ({ resourceTypes: [I.CONVERSATION], with: n }), p = async (n, t, s) => await fetch(n, {
|
|
83
83
|
method: s.method || "GET",
|
|
84
84
|
headers: t,
|
|
85
85
|
body: s?.isFormData && typeof s?.body == "string" ? s.body : JSON.stringify(s.body),
|
|
@@ -95,24 +95,24 @@ class k {
|
|
|
95
95
|
constructor() {
|
|
96
96
|
this.decoder = new TextDecoder();
|
|
97
97
|
}
|
|
98
|
-
async streamChat(t, s, e = {},
|
|
99
|
-
const { onMessage: a, onError:
|
|
98
|
+
async streamChat(t, s, e = {}, o) {
|
|
99
|
+
const { onMessage: a, onError: r, onComplete: c, signal: i } = e;
|
|
100
100
|
try {
|
|
101
101
|
const d = await this.initializeStreamRequest(
|
|
102
102
|
t,
|
|
103
103
|
s,
|
|
104
104
|
i,
|
|
105
|
-
|
|
105
|
+
o
|
|
106
106
|
);
|
|
107
107
|
await this.processStreamData(d, a), c?.();
|
|
108
108
|
} catch (d) {
|
|
109
|
-
this.handleStreamError(d,
|
|
109
|
+
this.handleStreamError(d, r);
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
|
-
async initializeStreamRequest(t, s, e,
|
|
112
|
+
async initializeStreamRequest(t, s, e, o) {
|
|
113
113
|
const a = S(void 0, {
|
|
114
|
-
jwt:
|
|
115
|
-
}),
|
|
114
|
+
jwt: o
|
|
115
|
+
}), r = await p(
|
|
116
116
|
t,
|
|
117
117
|
{
|
|
118
118
|
Accept: "text/event-stream",
|
|
@@ -124,37 +124,37 @@ class k {
|
|
|
124
124
|
signal: e
|
|
125
125
|
}
|
|
126
126
|
);
|
|
127
|
-
if (!
|
|
128
|
-
const c = await
|
|
127
|
+
if (!r.ok) {
|
|
128
|
+
const c = await r.text();
|
|
129
129
|
let i = {};
|
|
130
130
|
try {
|
|
131
131
|
i = JSON.parse(c);
|
|
132
132
|
} catch {
|
|
133
133
|
i.error = "Failed to parse error body";
|
|
134
134
|
}
|
|
135
|
-
throw new
|
|
136
|
-
status:
|
|
135
|
+
throw new _({
|
|
136
|
+
status: r.status,
|
|
137
137
|
message: i.error ?? "No response body"
|
|
138
138
|
});
|
|
139
139
|
}
|
|
140
|
-
if (!
|
|
141
|
-
throw new
|
|
140
|
+
if (!r.body)
|
|
141
|
+
throw new _({
|
|
142
142
|
message: "No response body",
|
|
143
|
-
status:
|
|
143
|
+
status: r.status
|
|
144
144
|
});
|
|
145
|
-
return
|
|
145
|
+
return r.body.getReader();
|
|
146
146
|
}
|
|
147
147
|
async processStreamData(t, s) {
|
|
148
148
|
let e = "";
|
|
149
149
|
try {
|
|
150
150
|
for (; ; ) {
|
|
151
|
-
const { done:
|
|
152
|
-
if (
|
|
151
|
+
const { done: o, value: a } = await t.read();
|
|
152
|
+
if (o) {
|
|
153
153
|
e.trim() && this.parseSSEDataLine(e, s);
|
|
154
154
|
break;
|
|
155
155
|
}
|
|
156
|
-
const
|
|
157
|
-
e +=
|
|
156
|
+
const r = this.decoder.decode(a, { stream: !0 });
|
|
157
|
+
e += r;
|
|
158
158
|
const c = e.split(`
|
|
159
159
|
`);
|
|
160
160
|
e = c.pop() || "";
|
|
@@ -172,33 +172,33 @@ class k {
|
|
|
172
172
|
parseSSEDataLine(t, s) {
|
|
173
173
|
const e = t.trim();
|
|
174
174
|
if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
|
|
175
|
-
const
|
|
176
|
-
if (
|
|
175
|
+
const o = e.slice(6);
|
|
176
|
+
if (o === "[DONE]") {
|
|
177
177
|
console.info("SSE: Stream completed");
|
|
178
178
|
return;
|
|
179
179
|
}
|
|
180
180
|
let a;
|
|
181
181
|
try {
|
|
182
|
-
a = JSON.parse(
|
|
183
|
-
} catch (
|
|
184
|
-
console.error(`Failed to parse SSE data: ${
|
|
182
|
+
a = JSON.parse(o);
|
|
183
|
+
} catch (r) {
|
|
184
|
+
console.error(`Failed to parse SSE data: ${o} ${r}`);
|
|
185
185
|
}
|
|
186
186
|
s?.(a);
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
|
-
const F = new k(), G = async (n, t, s, e,
|
|
191
|
-
const { onMessage: a, onToken:
|
|
190
|
+
const F = new k(), G = async (n, t, s, e, o) => {
|
|
191
|
+
const { onMessage: a, onToken: r, onComplete: c, onError: i, model: d, signal: m } = s, O = {
|
|
192
192
|
conversationId: n,
|
|
193
193
|
messages: t,
|
|
194
194
|
model: d,
|
|
195
|
-
custom_fields:
|
|
195
|
+
custom_fields: o
|
|
196
196
|
};
|
|
197
197
|
await F.streamChat(
|
|
198
198
|
V.CHAT,
|
|
199
199
|
O,
|
|
200
200
|
{
|
|
201
|
-
onMessage: (
|
|
201
|
+
onMessage: (C) => $(C, a, r),
|
|
202
202
|
onComplete: c,
|
|
203
203
|
onError: i,
|
|
204
204
|
signal: m
|
|
@@ -211,23 +211,23 @@ class Y {
|
|
|
211
211
|
this.client = t;
|
|
212
212
|
}
|
|
213
213
|
async getConversations(t, s, e) {
|
|
214
|
-
const
|
|
214
|
+
const o = `${s ? e ? `${s}/${e}` : `${s}` : ""}`, a = `${u.CONVERSATIONS}/${o}`;
|
|
215
215
|
try {
|
|
216
216
|
return (await this.client.getRequest(a + "/?limit=1000&recursive=false", t).then((c) => c.items || [])).map((c) => {
|
|
217
217
|
const { conversationName: i, modelId: d } = M(c);
|
|
218
218
|
return {
|
|
219
219
|
id: c.url?.replace("conversations/", "") || c.name,
|
|
220
220
|
name: i,
|
|
221
|
-
folderId:
|
|
221
|
+
folderId: o,
|
|
222
222
|
createdAt: c.createdAt,
|
|
223
223
|
updatedAt: c.updatedAt,
|
|
224
224
|
model: { id: d, name: d }
|
|
225
225
|
};
|
|
226
226
|
});
|
|
227
|
-
} catch (
|
|
228
|
-
if (l(
|
|
227
|
+
} catch (r) {
|
|
228
|
+
if (l(r))
|
|
229
229
|
return [];
|
|
230
|
-
throw
|
|
230
|
+
throw r;
|
|
231
231
|
}
|
|
232
232
|
}
|
|
233
233
|
async getConversation(t, s) {
|
|
@@ -252,22 +252,22 @@ class Y {
|
|
|
252
252
|
throw e;
|
|
253
253
|
}
|
|
254
254
|
}
|
|
255
|
-
async putOnboardingFile(t, s, e,
|
|
255
|
+
async putOnboardingFile(t, s, e, o) {
|
|
256
256
|
try {
|
|
257
|
-
const a = `${u.VERSION}/${h(s)}`,
|
|
258
|
-
`--${
|
|
257
|
+
const a = `${u.VERSION}/${h(s)}`, r = "----NodeMultipartBoundary", i = [
|
|
258
|
+
`--${r}`,
|
|
259
259
|
`Content-Disposition: form-data; name="file"; filename="${t}"`,
|
|
260
260
|
"Content-Type: application/json",
|
|
261
261
|
"",
|
|
262
262
|
JSON.stringify(e),
|
|
263
|
-
`--${
|
|
263
|
+
`--${r}--`,
|
|
264
264
|
""
|
|
265
265
|
].join(`\r
|
|
266
266
|
`);
|
|
267
|
-
return await this.client.request(a,
|
|
267
|
+
return await this.client.request(a, o, {
|
|
268
268
|
method: "PUT",
|
|
269
269
|
body: i,
|
|
270
|
-
headers: U(
|
|
270
|
+
headers: U(r),
|
|
271
271
|
isFormData: !0
|
|
272
272
|
});
|
|
273
273
|
} catch (a) {
|
|
@@ -297,11 +297,11 @@ class Y {
|
|
|
297
297
|
}
|
|
298
298
|
}
|
|
299
299
|
async createConversation(t, s) {
|
|
300
|
-
const e = t?.id || j(t), { name:
|
|
300
|
+
const e = t?.id || j(t), { name: o, folderId: a, model: r, messages: c, custom_fields: i } = t, d = {
|
|
301
301
|
id: e,
|
|
302
|
-
name:
|
|
302
|
+
name: o,
|
|
303
303
|
folderId: a,
|
|
304
|
-
model:
|
|
304
|
+
model: r,
|
|
305
305
|
messages: c || [],
|
|
306
306
|
selectedAddons: t.selectedAddons || [],
|
|
307
307
|
prompt: t.prompt || "",
|
|
@@ -319,9 +319,9 @@ class Y {
|
|
|
319
319
|
}
|
|
320
320
|
), {
|
|
321
321
|
id: e,
|
|
322
|
-
name:
|
|
322
|
+
name: o,
|
|
323
323
|
folderId: a,
|
|
324
|
-
model:
|
|
324
|
+
model: r,
|
|
325
325
|
createdAt: d.createdAt,
|
|
326
326
|
updatedAt: d.updatedAt
|
|
327
327
|
};
|
|
@@ -354,11 +354,11 @@ class Y {
|
|
|
354
354
|
);
|
|
355
355
|
}
|
|
356
356
|
async updateConversation(t, s, e) {
|
|
357
|
-
const
|
|
358
|
-
if (!
|
|
357
|
+
const o = await this.getConversation(t, e);
|
|
358
|
+
if (!o)
|
|
359
359
|
throw new Error(`Conversation with id ${t} not found`);
|
|
360
360
|
const a = {
|
|
361
|
-
...
|
|
361
|
+
...o,
|
|
362
362
|
...s,
|
|
363
363
|
updatedAt: Date.now()
|
|
364
364
|
};
|
|
@@ -389,7 +389,7 @@ class Y {
|
|
|
389
389
|
});
|
|
390
390
|
}
|
|
391
391
|
async streamChat(t, s) {
|
|
392
|
-
const e = t.model.id,
|
|
392
|
+
const e = t.model.id, o = encodeURIComponent(e), a = `${u.CHAT(o)}?api-version=${this.client.config.version}`, r = {
|
|
393
393
|
messages: t.messages,
|
|
394
394
|
stream: !0,
|
|
395
395
|
temperature: 0.7,
|
|
@@ -398,14 +398,14 @@ class Y {
|
|
|
398
398
|
};
|
|
399
399
|
return await this.client.stream(a, s, {
|
|
400
400
|
method: "POST",
|
|
401
|
-
body:
|
|
401
|
+
body: r,
|
|
402
402
|
chatReference: t.conversationId
|
|
403
403
|
});
|
|
404
404
|
}
|
|
405
|
-
async rateResponse(t, s, e,
|
|
405
|
+
async rateResponse(t, s, e, o) {
|
|
406
406
|
return await this.client.postRequest(
|
|
407
407
|
u.RATE(t),
|
|
408
|
-
|
|
408
|
+
o,
|
|
409
409
|
{
|
|
410
410
|
body: {
|
|
411
411
|
responseId: s,
|
|
@@ -439,7 +439,7 @@ class W {
|
|
|
439
439
|
return this.request(t, s, { ...e, method: "POST" });
|
|
440
440
|
}
|
|
441
441
|
async requestBlob(t, s, e) {
|
|
442
|
-
const
|
|
442
|
+
const o = `${this.config.host}${t}`, a = {
|
|
443
443
|
...S(this.config.apiKey, {
|
|
444
444
|
jwt: s,
|
|
445
445
|
chatReference: e.chatReference
|
|
@@ -447,26 +447,26 @@ class W {
|
|
|
447
447
|
...e.headers
|
|
448
448
|
};
|
|
449
449
|
try {
|
|
450
|
-
return (await p(
|
|
451
|
-
} catch (
|
|
450
|
+
return (await p(o, a, e)).blob();
|
|
451
|
+
} catch (r) {
|
|
452
452
|
throw console.error("API Request Exception", {
|
|
453
453
|
method: e.method,
|
|
454
|
-
url:
|
|
455
|
-
error:
|
|
456
|
-
}),
|
|
454
|
+
url: o,
|
|
455
|
+
error: r instanceof Error ? r.message : String(r)
|
|
456
|
+
}), r;
|
|
457
457
|
}
|
|
458
458
|
}
|
|
459
459
|
async request(t, s, e) {
|
|
460
|
-
const
|
|
460
|
+
const o = Date.now(), a = `${this.config.host}${t}`, r = {
|
|
461
461
|
...S(this.config.apiKey, {
|
|
462
462
|
jwt: s,
|
|
463
463
|
chatReference: e.chatReference
|
|
464
464
|
}),
|
|
465
465
|
...e.headers
|
|
466
466
|
};
|
|
467
|
-
this.addInfoRequestLog("API Request", a, e,
|
|
467
|
+
this.addInfoRequestLog("API Request", a, e, r);
|
|
468
468
|
try {
|
|
469
|
-
const c = await p(a,
|
|
469
|
+
const c = await p(a, r, e), i = Date.now() - o;
|
|
470
470
|
let d;
|
|
471
471
|
const m = await c.text();
|
|
472
472
|
try {
|
|
@@ -491,7 +491,7 @@ class W {
|
|
|
491
491
|
}
|
|
492
492
|
return d;
|
|
493
493
|
} catch (c) {
|
|
494
|
-
const i = Date.now() -
|
|
494
|
+
const i = Date.now() - o;
|
|
495
495
|
throw console.error("API Request Exception", {
|
|
496
496
|
method: e.method,
|
|
497
497
|
url: a,
|
|
@@ -501,7 +501,7 @@ class W {
|
|
|
501
501
|
}
|
|
502
502
|
}
|
|
503
503
|
async stream(t, s, e) {
|
|
504
|
-
const
|
|
504
|
+
const o = `${this.config.host}${t}`, a = S(
|
|
505
505
|
this.config.apiKey,
|
|
506
506
|
{
|
|
507
507
|
jwt: s,
|
|
@@ -509,46 +509,46 @@ class W {
|
|
|
509
509
|
},
|
|
510
510
|
e.headers
|
|
511
511
|
);
|
|
512
|
-
this.addInfoRequestLog("Stream Request",
|
|
513
|
-
const
|
|
514
|
-
if (!
|
|
512
|
+
this.addInfoRequestLog("Stream Request", o, e, a);
|
|
513
|
+
const r = await p(o, a, e);
|
|
514
|
+
if (!r.ok)
|
|
515
515
|
throw console.error("Stream Request Failed", {
|
|
516
516
|
method: e.method || "POST",
|
|
517
|
-
url:
|
|
518
|
-
status:
|
|
519
|
-
statusText:
|
|
517
|
+
url: o,
|
|
518
|
+
status: r.status,
|
|
519
|
+
statusText: r.statusText
|
|
520
520
|
}), new Error(
|
|
521
|
-
`Stream request failed: ${
|
|
521
|
+
`Stream request failed: ${r.status} ${r.statusText}`
|
|
522
522
|
);
|
|
523
|
-
if (!
|
|
523
|
+
if (!r.body)
|
|
524
524
|
throw new Error("No response body for stream");
|
|
525
|
-
return
|
|
525
|
+
return r.body;
|
|
526
526
|
}
|
|
527
|
-
addInfoRequestLog(t, s, e,
|
|
527
|
+
addInfoRequestLog(t, s, e, o) {
|
|
528
528
|
const a = {
|
|
529
529
|
method: e.method || "GET",
|
|
530
530
|
url: s,
|
|
531
|
-
headers: L(
|
|
531
|
+
headers: L(o)
|
|
532
532
|
};
|
|
533
533
|
e.body && (a.body = e.body), console.info(t, a);
|
|
534
534
|
}
|
|
535
|
-
addErrorRequestLog(t, s, e,
|
|
535
|
+
addErrorRequestLog(t, s, e, o, a) {
|
|
536
536
|
console.error("API Request Failed", {
|
|
537
537
|
method: s.method,
|
|
538
538
|
url: t,
|
|
539
539
|
status: e.status,
|
|
540
540
|
statusText: e.statusText,
|
|
541
|
-
duration: `${
|
|
541
|
+
duration: `${o}ms`,
|
|
542
542
|
response: a
|
|
543
543
|
});
|
|
544
544
|
}
|
|
545
|
-
addErrorRequestParsing(t, s, e,
|
|
545
|
+
addErrorRequestParsing(t, s, e, o, a) {
|
|
546
546
|
console.error("API Response Parse Error", {
|
|
547
547
|
method: s.method,
|
|
548
548
|
url: t,
|
|
549
549
|
status: e.status,
|
|
550
550
|
statusText: e.statusText,
|
|
551
|
-
duration: `${
|
|
551
|
+
duration: `${o}ms`,
|
|
552
552
|
responseText: a.substring(0, 200),
|
|
553
553
|
// First 200 chars
|
|
554
554
|
error: "Response is not valid JSON"
|
|
@@ -563,8 +563,8 @@ export {
|
|
|
563
563
|
K as DIAL_ERROR_CODES,
|
|
564
564
|
W as DialApiClient,
|
|
565
565
|
g as InvitationType,
|
|
566
|
-
|
|
567
|
-
|
|
566
|
+
I as ResourceTypes,
|
|
567
|
+
N as ShareTarget,
|
|
568
568
|
F as chatStreamSSEClient,
|
|
569
569
|
z as decodeApiUrl,
|
|
570
570
|
h as encodeApiUrl,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@epam/statgpt-dial-toolkit",
|
|
3
|
-
"version": "0.2.0-rc.
|
|
3
|
+
"version": "0.2.0-rc.46",
|
|
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.
|
|
17
|
+
"@epam/statgpt-shared-toolkit": "0.2.0-rc.46",
|
|
18
18
|
"@epam/ai-dial-shared": "^0.34.0"
|
|
19
19
|
}
|
|
20
20
|
}
|