@epam/statgpt-dial-toolkit 0.5.0-rc.13 → 0.5.0-rc.15
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/constants/api-urls.d.ts +1 -0
- package/index.cjs +1 -1
- package/index.mjs +96 -95
- package/package.json +2 -2
package/constants/api-urls.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export declare const DIAL_API_ROUTES: {
|
|
|
7
7
|
readonly MODELS: "/openai/models";
|
|
8
8
|
readonly CONFIGURATION: (modelId: string) => string;
|
|
9
9
|
readonly DATASETS_METADATA: (deploymentId: string) => string;
|
|
10
|
+
readonly PYTHON_ATTACHMENT: (deploymentId: string) => string;
|
|
10
11
|
readonly SHARE_CONVERSATION: "/v1/ops/resource/share/create";
|
|
11
12
|
readonly SHARE_CONVERSATION_ACCEPT: (invitationId: string) => string;
|
|
12
13
|
readonly SHARE_CONVERSATION_DETAILS: (invitationId: string) => string;
|
package/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",S=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${l}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${l}/deployments/${s}/configuration`,DATASETS_METADATA:s=>`/v1/deployments/${s}/route/metadata/datasets`,SHARE_CONVERSATION:`${S}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${S}/list`,SHARE_CONVERSATION_DISCARD:`${S}/discard`,SHARE_CONVERSATION_REVOKE:`${S}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},H={LENGTH:"length",STOP:"stop"},R={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},U={CONTENT_FILTER:"content_filter",500:"500"},V={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},x=[R.MINUTE,R.DAILY,R.WEEKLY,R.MONTHLY],F="statgpt",N={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(s=>(s.CONVERSATION="CONVERSATION",s))(O||{}),g=(s=>(s.ME="me",s.OTHERS="others",s))(g||{}),y=(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.CROSS_DATASET_GRID="cross_dataset_grid",s.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s.CUSTOM_CODE_SAMPLE="custom_code_sample",s))(y||{}),$=(s=>(s.LINK="link",s))($||{});const K=s=>s.content?(console.info(`Using direct content format: ${s.content}`),s.content):s.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):s.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${s.choices[0].message.content}`),s.choices[0].message.content):(console.info("Unknown SSE data format:",s),null),D=(s,t,n)=>{if(t?.(s),n){const e=K(s);e&&n(e)}},v=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,j=(s,t)=>{const n=s?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},k=(s,t)=>{const n=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&Y(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=j(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function Y(s,t){if(t.content){const n=B(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function B(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const G={CHAT:"/api/chat"},J="application/json",X="Content-Type",T="Api-Key",z="X-CONVERSATION-ID",I="Ocp-Apim-Subscription-Key";class C extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details,this.displayMessage=t.displayMessage}}const W=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Q=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)W(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},p=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[X]=t?.contentType||J),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[T]=s),t?.chatReference&&(e[z]=t.chatReference),{...e,...n}},Z=s=>{const t={...s};return t[T]&&(t[T]=t[T].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[I]&&(t[I]=t[I].substring(0,8)+"...[REDACTED]"),t},ee=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),w=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},L=s=>{const t=Date.now(),n=Q(s.name);return`${s.folderId}/${n}-${t}`},te=s=>({resourceTypes:[O.CONVERSATION],with:s}),f=async(s,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(s,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function E(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function ne(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function b(s){if(s?.kind!==N.RATE_LIMIT||typeof s.retryAfterSeconds!="number")return null;const t=new Date(s.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+s.retryAfterSeconds*1e3)}function se(s,t=Date.now()){const n=b(s);return n?n.getTime()>t:!1}function re(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:a,onError:o,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,a),i?.()}catch(u){this.handleStreamError(u,o)}}async initializeStreamRequest(t,n,e,r){const a=p(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:n,signal:e});if(!o.ok){const i=await o.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new C({status:o.status,message:c.error??"No response body"})}if(!o.body)throw new C({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const i=e.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",S=`/${l}/ops/resource/share`,d={VERSION:`/${l}`,BUCKET:`/${l}/bucket`,CONVERSATIONS:`/${l}/metadata/conversations`,CONVERSATION_BY_ID:s=>`/${l}/metadata/conversations/${s}`,CHAT:s=>`/openai/deployments/${s}/chat/completions`,MODELS:"/openai/models",CONFIGURATION:s=>`/${l}/deployments/${s}/configuration`,DATASETS_METADATA:s=>`/v1/deployments/${s}/route/metadata/datasets`,PYTHON_ATTACHMENT:s=>`/v1/deployments/${s}/route/python-attachment`,SHARE_CONVERSATION:`${S}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${S}/list`,SHARE_CONVERSATION_DISCARD:`${S}/discard`,SHARE_CONVERSATION_REVOKE:`${S}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},H={LENGTH:"length",STOP:"stop"},R={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},U={CONTENT_FILTER:"content_filter",500:"500"},V={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},x=[R.MINUTE,R.DAILY,R.WEEKLY,R.MONTHLY],F="statgpt",N={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var O=(s=>(s.CONVERSATION="CONVERSATION",s))(O||{}),g=(s=>(s.ME="me",s.OTHERS="others",s))(g||{}),y=(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.CROSS_DATASET_GRID="cross_dataset_grid",s.CUSTOM_DATA_GRID="custom_data_grid",s.CUSTOM_CHART="custom_chart",s.CUSTOM_CODE_SAMPLE="custom_code_sample",s))(y||{}),$=(s=>(s.LINK="link",s))($||{});const K=s=>s.content?(console.info(`Using direct content format: ${s.content}`),s.content):s.choices?.[0]?.delta?.content?(console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`),s.choices[0].delta.content):s.choices?.[0]?.message?.content?(console.info(`Using complete message format: ${s.choices[0].message.content}`),s.choices[0].message.content):(console.info("Unknown SSE data format:",s),null),D=(s,t,n)=>{if(t?.(s),n){const e=K(s);e&&n(e)}},v=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,j=(s,t)=>{const n=s?.reduce((e,r)=>(e[r.index]=r,e),{});return t.forEach(e=>{n[e.index]?(e.attachments&&(n[e.index].attachments=(n[e.index].attachments||[]).concat(e.attachments)),e.content&&(n[e.index].content=(n[e.index].content||"")+e.content),e.name&&(n[e.index].name=(n[e.index].name||"")+e.name),e.status&&(n[e.index].status=e.status)):n[e.index]=e}),Object.values(n)},k=(s,t)=>{const n=structuredClone(s);return t.forEach(e=>{e.errorMessage&&(n.errorMessage=e.errorMessage),e.role&&(n.role=e.role),e.responseId&&(n.responseId=e.responseId),e.content&&Y(n,e),e.custom_content&&(n.custom_content||(n.custom_content={}),e.custom_content.attachments&&(n.custom_content.attachments||(n.custom_content.attachments=[]),n.custom_content.attachments=n.custom_content.attachments.concat(e.custom_content.attachments)),e.custom_content.stages&&(n.custom_content.stages||(n.custom_content.stages=[]),n.custom_content.stages=j(n.custom_content.stages,e.custom_content.stages)),e.custom_content.state&&(n.custom_content.state=e.custom_content.state),e.custom_content.form_schema&&(n.custom_content.form_schema=e.custom_content.form_schema),e.custom_content.form_value&&(n.custom_content.form_value=e.custom_content.form_value))}),n};function Y(s,t){if(t.content){const n=B(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function B(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const G={CHAT:"/api/chat"},J="application/json",X="Content-Type",T="Api-Key",z="X-CONVERSATION-ID",I="Ocp-Apim-Subscription-Key";class C extends Error{constructor(t){super(t.message),this.isHttpError=!0,this.name="HttpError",this.code=t.code,this.status=t.status,this.details=t.details,this.displayMessage=t.displayMessage}}const W=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Q=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)W(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},p=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[X]=t?.contentType||J),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[T]=s),t?.chatReference&&(e[z]=t.chatReference),{...e,...n}},Z=s=>{const t={...s};return t[T]&&(t[T]=t[T].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[I]&&(t[I]=t[I].substring(0,8)+"...[REDACTED]"),t},ee=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),w=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},L=s=>{const t=Date.now(),n=Q(s.name);return`${s.folderId}/${n}-${t}`},te=s=>({resourceTypes:[O.CONVERSATION],with:s}),f=async(s,t,n)=>{const e=n?.body===void 0?void 0:n?.isFormData?n.body:JSON.stringify(n.body);return await fetch(s,{method:n.method||"GET",headers:t,body:e,signal:n?.signal})};function E(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function ne(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function b(s){if(s?.kind!==N.RATE_LIMIT||typeof s.retryAfterSeconds!="number")return null;const t=new Date(s.occurredAt).getTime();return Number.isNaN(t)?null:new Date(t+s.retryAfterSeconds*1e3)}function se(s,t=Date.now()){const n=b(s);return n?n.getTime()>t:!1}function re(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class q{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:a,onError:o,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,a),i?.()}catch(u){this.handleStreamError(u,o)}}async initializeStreamRequest(t,n,e,r){const a=p(void 0,{jwt:r}),o=await f(t,{Accept:"text/event-stream",...a},{method:"POST",body:n,signal:e});if(!o.ok){const i=await o.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new C({status:o.status,message:c.error??"No response body"})}if(!o.body)throw new C({message:"No response body",status:o.status});return o.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:a}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const o=this.decoder.decode(a,{stream:!0});e+=o;const i=e.split(`
|
|
2
2
|
`);e=i.pop()||"";for(const c of i)this.parseSSEDataLine(c,n)}}finally{t.releaseLock()}}handleStreamError(t,n){const e=t instanceof Error?t:new Error(String(t));throw n?.(e),e}parseSSEDataLine(t,n){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}`)}n?.(a)}}}const M=new q,oe=async(s,t,n,e,r)=>{const{onMessage:a,onToken:o,onComplete:i,onError:c,model:u,signal:h}=n,A={conversationId:s,messages:t,model:u,custom_fields:r};await M.streamChat(G.CHAT,A,{onMessage:P=>D(P,a,o),onComplete:i,onError:c,signal:h},e)},m=s=>s instanceof Error&&s.message.includes("404"),_=s=>`/v1/conversations/${E(s)}`;class ae{constructor(t){this.client=t}async getConversations(t,n,e){const r=`${n?e?`${n}/${e}`:`${n}`:""}`,a=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(a+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=w(i);return{id:i.url?.replace("conversations/","")||i.name,name:c,folderId:r,createdAt:i.createdAt,updatedAt:i.updatedAt,model:{id:u,name:u}}})}catch(o){if(m(o))return[];throw o}}async getConversation(t,n){try{return await this.client.getRequest(_(t),n)}catch(e){if(m(e))return null;throw e}}async getFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return null;throw e}}async putOnboardingFile(t,n,e,r){try{const a=`${d.VERSION}/${E(n)}`,o="----NodeMultipartBoundary",c=[`--${o}`,`Content-Disposition: form-data; name="file"; filename="${t}"`,"Content-Type: application/json","",JSON.stringify(e),`--${o}--`,""].join(`\r
|
|
3
3
|
`);return await this.client.request(a,r,{method:"PUT",body:c,headers:ee(o),isFormData:!0})}catch(a){if(m(a))return null;throw a}}async getOnboardingFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return null;throw e}}async getFileBlob(t,n){try{const e=`${d.VERSION}/${E(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(m(e))return null;throw e}}async deleteFile(t,n){try{const e=`${d.VERSION}/${E(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(m(e))return;throw e}}async putFile(t,n,e){try{const r=`${d.VERSION}/${E(t)}`,a=new FormData,o=decodeURIComponent(t.split("/").at(-1)??"file");a.append("attachment",n,o),await this.client.request(r,e,{method:"PUT",body:a,isFormData:!0})}catch(r){if(m(r))return;throw r}}async createConversation(t,n){const e=t?.id||L(t),{name:r,folderId:a,model:o,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:a,model:o,messages:i||[],selectedAddons:t.selectedAddons||[],prompt:t.prompt||"",temperature:t.temperature||.7,createdAt:Date.now(),updatedAt:Date.now(),custom_fields:c};return await this.client.request(_(e),n,{method:"PUT",body:u}),{id:e,name:r,folderId:a,model:o,createdAt:u.createdAt,updatedAt:u.updatedAt}}async generateConversationLink(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION,t,{body:n})}async getSharedConversations(t,n){return await this.client.postRequest(d.SHARE_CONVERSATION_LIST,t,{body:n})}async revokeSharedConversations(t,n){await this.client.postRequest(d.SHARE_CONVERSATION_REVOKE,t,{body:n})}async updateConversation(t,n,e){const r=await this.getConversation(t,e);if(!r)throw new Error(`Conversation with id ${t} not found`);const a={...r,...n,updatedAt:Date.now()};return await this.client.request(_(t),e,{method:"PUT",body:a})}async deleteConversation(t,n,e){n?.isShared?await this.client.postRequest(d.SHARE_CONVERSATION_DISCARD,e,{body:{resources:[{url:n?.url}]}}):await this.client.request(_(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,r=encodeURIComponent(e),a=`${d.CHAT(r)}?api-version=${this.client.config.version}`,o={messages:t.messages,stream:!0,temperature:.7,max_tokens:4096,custom_fields:t.custom_fields};return await this.client.stream(a,n,{method:"POST",body:o,chatReference:t.conversationId})}async rateResponse(t,n,e,r){return await this.client.postRequest(d.RATE(t),r,{body:{responseId:n,rate:e}})}async renameConversation(t,n,e){return await this.client.postRequest(d.RENAME,e,{body:{sourceUrl:t,destinationUrl:n,overwrite:!0}})}}class ie{constructor(t){this.config=t,console.info("DialApiClient initialized",{host:t.host||"NOT SET",hasApiKey:!!t.apiKey,version:t.version})}async getRequest(t,n,e){return this.request(t,n,{...e,method:"GET"})}async postRequest(t,n,e){return this.request(t,n,{...e,method:"POST"})}async requestBlob(t,n,e){const r=`${this.config.host}${t}`,a={...p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...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,n,e){const r=Date.now(),a=`${this.config.host}${t}`,o={...p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",a,e,o);try{const i=await f(a,o,e),c=Date.now()-r;let u;const h=await i.text();try{u=h?JSON.parse(h):{}}catch{if(this.addErrorRequestParsing(a,e,i,c,h),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${h.substring(0,100)}`);u={data:h}}if(!i.ok){this.addErrorRequestLog(a,e,i,c,u);const A=v(u,i);throw new Error(`API request failed: ${A}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:a,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const r=`${this.config.host}${t}`,a=p(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},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,n,e,r){const a={method:e.method||"GET",url:n,headers:Z(r)};e.body&&(a.body=e.body),console.info(t,a)}addErrorRequestLog(t,n,e,r,a){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:a})}addErrorRequestParsing(t,n,e,r,a){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:a.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=y;exports.COMPLETION_FINISH_REASON=H;exports.CUSTOM_VIEW_STATE_KEY=F;exports.ChatStreamSSEClient=q;exports.ConversationApi=ae;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=U;exports.DIAL_ERROR_TYPES=V;exports.DialApiClient=ie;exports.ERROR_CONTEXT_KIND=N;exports.EXCEEDED_LIMIT=R;exports.EXCEEDED_LIMIT_ORDER=x;exports.InvitationType=$;exports.ResourceTypes=O;exports.ShareTarget=g;exports.chatStreamSSEClient=M;exports.decodeApiUrl=ne;exports.encodeApiUrl=E;exports.formatDateTime=re;exports.generateConversationId=L;exports.getErrorMessage=v;exports.getRateLimitRestoreDate=b;exports.getSharedConversationsRequest=te;exports.handleStreamMessage=D;exports.isRateLimitStillActive=se;exports.mergeMessages=k;exports.parseConversationName=w;exports.sendRequest=f;exports.streamChatResponse=oe;
|
package/index.mjs
CHANGED
|
@@ -7,6 +7,7 @@ const h = "/v1/ops/resource/share", d = {
|
|
|
7
7
|
MODELS: "/openai/models",
|
|
8
8
|
CONFIGURATION: (s) => `/v1/deployments/${s}/configuration`,
|
|
9
9
|
DATASETS_METADATA: (s) => `/v1/deployments/${s}/route/metadata/datasets`,
|
|
10
|
+
PYTHON_ATTACHMENT: (s) => `/v1/deployments/${s}/route/python-attachment`,
|
|
10
11
|
SHARE_CONVERSATION: `${h}/create`,
|
|
11
12
|
SHARE_CONVERSATION_ACCEPT: (s) => `/v1/invitations/${s}?accept=true`,
|
|
12
13
|
SHARE_CONVERSATION_DETAILS: (s) => `/v1/invitations/${s}`,
|
|
@@ -34,11 +35,11 @@ const h = "/v1/ops/resource/share", d = {
|
|
|
34
35
|
R.DAILY,
|
|
35
36
|
R.WEEKLY,
|
|
36
37
|
R.MONTHLY
|
|
37
|
-
], Q = "statgpt",
|
|
38
|
+
], Q = "statgpt", y = {
|
|
38
39
|
RATE_LIMIT: "rate_limit",
|
|
39
40
|
UNKNOWN: "unknown"
|
|
40
41
|
};
|
|
41
|
-
var A = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(A || {}),
|
|
42
|
+
var A = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(A || {}), C = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(C || {}), g = /* @__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.CROSS_DATASET_GRID = "cross_dataset_grid", s.CUSTOM_DATA_GRID = "custom_data_grid", s.CUSTOM_CHART = "custom_chart", s.CUSTOM_CODE_SAMPLE = "custom_code_sample", s))(g || {}), $ = /* @__PURE__ */ ((s) => (s.LINK = "link", s))($ || {});
|
|
42
43
|
const w = (s) => s.content ? (console.info(`Using direct content format: ${s.content}`), s.content) : s.choices?.[0]?.delta?.content ? (console.info(`Using OpenAI delta format: ${s.choices[0].delta.content}`), s.choices[0].delta.content) : s.choices?.[0]?.message?.content ? (console.info(
|
|
43
44
|
`Using complete message format: ${s.choices[0].message.content}`
|
|
44
45
|
), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null), v = (s, e, n) => {
|
|
@@ -48,7 +49,7 @@ const w = (s) => s.content ? (console.info(`Using direct content format: ${s.con
|
|
|
48
49
|
}
|
|
49
50
|
}, D = (s, e) => s.error || s.message || `${e.status} ${e.statusText}`, b = (s, e) => {
|
|
50
51
|
const n = s?.reduce(
|
|
51
|
-
(t,
|
|
52
|
+
(t, o) => (t[o.index] = o, t),
|
|
52
53
|
{}
|
|
53
54
|
);
|
|
54
55
|
return e.forEach((t) => {
|
|
@@ -77,7 +78,7 @@ function L(s) {
|
|
|
77
78
|
}
|
|
78
79
|
const V = {
|
|
79
80
|
CHAT: "/api/chat"
|
|
80
|
-
}, M = "application/json", P = "Content-Type", S = "Api-Key", H = "X-CONVERSATION-ID",
|
|
81
|
+
}, M = "application/json", P = "Content-Type", S = "Api-Key", H = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
|
|
81
82
|
class p extends Error {
|
|
82
83
|
constructor(e) {
|
|
83
84
|
super(e.message), this.isHttpError = !0, this.name = "HttpError", this.code = e.code, this.status = e.status, this.details = e.details, this.displayMessage = e.displayMessage;
|
|
@@ -87,15 +88,15 @@ const x = (s) => new RegExp("\\p{L}", "u").test(s) || new RegExp("\\p{N}", "u").
|
|
|
87
88
|
if (!s) return "";
|
|
88
89
|
const e = s.toLowerCase(), n = [];
|
|
89
90
|
let t = "";
|
|
90
|
-
for (const
|
|
91
|
-
x(
|
|
91
|
+
for (const o of e)
|
|
92
|
+
x(o) ? t += o : t && (n.push(t), t = "");
|
|
92
93
|
return t && n.push(t), n.join(" ");
|
|
93
94
|
}, _ = (s, e, n) => {
|
|
94
95
|
const t = {};
|
|
95
96
|
return e?.contentType !== null && (t[P] = e?.contentType || M), e?.jwt ? t.Authorization = `Bearer ${e.jwt}` : s && (t[S] = s), e?.chatReference && (t[H] = e.chatReference), { ...t, ...n };
|
|
96
97
|
}, F = (s) => {
|
|
97
98
|
const e = { ...s };
|
|
98
|
-
return e[S] && (e[S] = e[S].substring(0, 8) + "...[REDACTED]"), e.Authorization && (e.Authorization = "Bearer [REDACTED]"), e[
|
|
99
|
+
return e[S] && (e[S] = e[S].substring(0, 8) + "...[REDACTED]"), e.Authorization && (e.Authorization = "Bearer [REDACTED]"), e[I] && (e[I] = e[I].substring(0, 8) + "...[REDACTED]"), e;
|
|
99
100
|
}, K = (s) => ({
|
|
100
101
|
"Content-Type": `multipart/form-data; boundary=${s}`
|
|
101
102
|
}), j = (s) => {
|
|
@@ -104,7 +105,7 @@ const x = (s) => new RegExp("\\p{L}", "u").test(s) || new RegExp("\\p{N}", "u").
|
|
|
104
105
|
}, k = (s) => {
|
|
105
106
|
const e = Date.now(), n = U(s.name);
|
|
106
107
|
return `${s.folderId}/${n}-${e}`;
|
|
107
|
-
}, tt = (s) => ({ resourceTypes: [A.CONVERSATION], with: s }),
|
|
108
|
+
}, tt = (s) => ({ resourceTypes: [A.CONVERSATION], with: s }), T = async (s, e, n) => {
|
|
108
109
|
const t = n?.body === void 0 ? void 0 : n?.isFormData ? n.body : JSON.stringify(n.body);
|
|
109
110
|
return await fetch(s, {
|
|
110
111
|
method: n.method || "GET",
|
|
@@ -120,7 +121,7 @@ function et(s) {
|
|
|
120
121
|
return s.split("/").map((e) => decodeURIComponent(e)).join("/");
|
|
121
122
|
}
|
|
122
123
|
function Y(s) {
|
|
123
|
-
if (s?.kind !==
|
|
124
|
+
if (s?.kind !== y.RATE_LIMIT || typeof s.retryAfterSeconds != "number")
|
|
124
125
|
return null;
|
|
125
126
|
const e = new Date(s.occurredAt).getTime();
|
|
126
127
|
return Number.isNaN(e) ? null : new Date(e + s.retryAfterSeconds * 1e3);
|
|
@@ -142,24 +143,24 @@ class B {
|
|
|
142
143
|
constructor() {
|
|
143
144
|
this.decoder = new TextDecoder();
|
|
144
145
|
}
|
|
145
|
-
async streamChat(e, n, t = {},
|
|
146
|
-
const { onMessage: a, onError:
|
|
146
|
+
async streamChat(e, n, t = {}, o) {
|
|
147
|
+
const { onMessage: a, onError: r, onComplete: c, signal: i } = t;
|
|
147
148
|
try {
|
|
148
149
|
const u = await this.initializeStreamRequest(
|
|
149
150
|
e,
|
|
150
151
|
n,
|
|
151
152
|
i,
|
|
152
|
-
|
|
153
|
+
o
|
|
153
154
|
);
|
|
154
155
|
await this.processStreamData(u, a), c?.();
|
|
155
156
|
} catch (u) {
|
|
156
|
-
this.handleStreamError(u,
|
|
157
|
+
this.handleStreamError(u, r);
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
|
-
async initializeStreamRequest(e, n, t,
|
|
160
|
+
async initializeStreamRequest(e, n, t, o) {
|
|
160
161
|
const a = _(void 0, {
|
|
161
|
-
jwt:
|
|
162
|
-
}),
|
|
162
|
+
jwt: o
|
|
163
|
+
}), r = await T(
|
|
163
164
|
e,
|
|
164
165
|
{
|
|
165
166
|
Accept: "text/event-stream",
|
|
@@ -171,8 +172,8 @@ class B {
|
|
|
171
172
|
signal: t
|
|
172
173
|
}
|
|
173
174
|
);
|
|
174
|
-
if (!
|
|
175
|
-
const c = await
|
|
175
|
+
if (!r.ok) {
|
|
176
|
+
const c = await r.text();
|
|
176
177
|
let i = {};
|
|
177
178
|
try {
|
|
178
179
|
i = JSON.parse(c);
|
|
@@ -180,28 +181,28 @@ class B {
|
|
|
180
181
|
i.error = "Failed to parse error body";
|
|
181
182
|
}
|
|
182
183
|
throw new p({
|
|
183
|
-
status:
|
|
184
|
+
status: r.status,
|
|
184
185
|
message: i.error ?? "No response body"
|
|
185
186
|
});
|
|
186
187
|
}
|
|
187
|
-
if (!
|
|
188
|
+
if (!r.body)
|
|
188
189
|
throw new p({
|
|
189
190
|
message: "No response body",
|
|
190
|
-
status:
|
|
191
|
+
status: r.status
|
|
191
192
|
});
|
|
192
|
-
return
|
|
193
|
+
return r.body.getReader();
|
|
193
194
|
}
|
|
194
195
|
async processStreamData(e, n) {
|
|
195
196
|
let t = "";
|
|
196
197
|
try {
|
|
197
198
|
for (; ; ) {
|
|
198
|
-
const { done:
|
|
199
|
-
if (
|
|
199
|
+
const { done: o, value: a } = await e.read();
|
|
200
|
+
if (o) {
|
|
200
201
|
t.trim() && this.parseSSEDataLine(t, n);
|
|
201
202
|
break;
|
|
202
203
|
}
|
|
203
|
-
const
|
|
204
|
-
t +=
|
|
204
|
+
const r = this.decoder.decode(a, { stream: !0 });
|
|
205
|
+
t += r;
|
|
205
206
|
const c = t.split(`
|
|
206
207
|
`);
|
|
207
208
|
t = c.pop() || "";
|
|
@@ -219,33 +220,33 @@ class B {
|
|
|
219
220
|
parseSSEDataLine(e, n) {
|
|
220
221
|
const t = e.trim();
|
|
221
222
|
if (!(!t || t.startsWith(":")) && t.startsWith("data: ")) {
|
|
222
|
-
const
|
|
223
|
-
if (
|
|
223
|
+
const o = t.slice(6);
|
|
224
|
+
if (o === "[DONE]") {
|
|
224
225
|
console.info("SSE: Stream completed");
|
|
225
226
|
return;
|
|
226
227
|
}
|
|
227
228
|
let a;
|
|
228
229
|
try {
|
|
229
|
-
a = JSON.parse(
|
|
230
|
-
} catch (
|
|
231
|
-
console.error(`Failed to parse SSE data: ${
|
|
230
|
+
a = JSON.parse(o);
|
|
231
|
+
} catch (r) {
|
|
232
|
+
console.error(`Failed to parse SSE data: ${o} ${r}`);
|
|
232
233
|
}
|
|
233
234
|
n?.(a);
|
|
234
235
|
}
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
|
-
const G = new B(),
|
|
238
|
-
const { onMessage: a, onToken:
|
|
238
|
+
const G = new B(), ot = async (s, e, n, t, o) => {
|
|
239
|
+
const { onMessage: a, onToken: r, onComplete: c, onError: i, model: u, signal: m } = n, O = {
|
|
239
240
|
conversationId: s,
|
|
240
241
|
messages: e,
|
|
241
242
|
model: u,
|
|
242
|
-
custom_fields:
|
|
243
|
+
custom_fields: o
|
|
243
244
|
};
|
|
244
245
|
await G.streamChat(
|
|
245
246
|
V.CHAT,
|
|
246
247
|
O,
|
|
247
248
|
{
|
|
248
|
-
onMessage: (N) => v(N, a,
|
|
249
|
+
onMessage: (N) => v(N, a, r),
|
|
249
250
|
onComplete: c,
|
|
250
251
|
onError: i,
|
|
251
252
|
signal: m
|
|
@@ -253,28 +254,28 @@ const G = new B(), rt = async (s, e, n, t, r) => {
|
|
|
253
254
|
t
|
|
254
255
|
);
|
|
255
256
|
}, l = (s) => s instanceof Error && s.message.includes("404"), f = (s) => `/v1/conversations/${E(s)}`;
|
|
256
|
-
class
|
|
257
|
+
class rt {
|
|
257
258
|
constructor(e) {
|
|
258
259
|
this.client = e;
|
|
259
260
|
}
|
|
260
261
|
async getConversations(e, n, t) {
|
|
261
|
-
const
|
|
262
|
+
const o = `${n ? t ? `${n}/${t}` : `${n}` : ""}`, a = `${d.CONVERSATIONS}/${o}`;
|
|
262
263
|
try {
|
|
263
264
|
return (await this.client.getRequest(a + "/?limit=1000&recursive=false", e).then((c) => c.items || [])).map((c) => {
|
|
264
265
|
const { conversationName: i, modelId: u } = j(c);
|
|
265
266
|
return {
|
|
266
267
|
id: c.url?.replace("conversations/", "") || c.name,
|
|
267
268
|
name: i,
|
|
268
|
-
folderId:
|
|
269
|
+
folderId: o,
|
|
269
270
|
createdAt: c.createdAt,
|
|
270
271
|
updatedAt: c.updatedAt,
|
|
271
272
|
model: { id: u, name: u }
|
|
272
273
|
};
|
|
273
274
|
});
|
|
274
|
-
} catch (
|
|
275
|
-
if (l(
|
|
275
|
+
} catch (r) {
|
|
276
|
+
if (l(r))
|
|
276
277
|
return [];
|
|
277
|
-
throw
|
|
278
|
+
throw r;
|
|
278
279
|
}
|
|
279
280
|
}
|
|
280
281
|
async getConversation(e, n) {
|
|
@@ -299,22 +300,22 @@ class ot {
|
|
|
299
300
|
throw t;
|
|
300
301
|
}
|
|
301
302
|
}
|
|
302
|
-
async putOnboardingFile(e, n, t,
|
|
303
|
+
async putOnboardingFile(e, n, t, o) {
|
|
303
304
|
try {
|
|
304
|
-
const a = `${d.VERSION}/${E(n)}`,
|
|
305
|
-
`--${
|
|
305
|
+
const a = `${d.VERSION}/${E(n)}`, r = "----NodeMultipartBoundary", i = [
|
|
306
|
+
`--${r}`,
|
|
306
307
|
`Content-Disposition: form-data; name="file"; filename="${e}"`,
|
|
307
308
|
"Content-Type: application/json",
|
|
308
309
|
"",
|
|
309
310
|
JSON.stringify(t),
|
|
310
|
-
`--${
|
|
311
|
+
`--${r}--`,
|
|
311
312
|
""
|
|
312
313
|
].join(`\r
|
|
313
314
|
`);
|
|
314
|
-
return await this.client.request(a,
|
|
315
|
+
return await this.client.request(a, o, {
|
|
315
316
|
method: "PUT",
|
|
316
317
|
body: i,
|
|
317
|
-
headers: K(
|
|
318
|
+
headers: K(r),
|
|
318
319
|
isFormData: !0
|
|
319
320
|
});
|
|
320
321
|
} catch (a) {
|
|
@@ -355,24 +356,24 @@ class ot {
|
|
|
355
356
|
}
|
|
356
357
|
async putFile(e, n, t) {
|
|
357
358
|
try {
|
|
358
|
-
const
|
|
359
|
-
a.append("attachment", n,
|
|
359
|
+
const o = `${d.VERSION}/${E(e)}`, a = new FormData(), r = decodeURIComponent(e.split("/").at(-1) ?? "file");
|
|
360
|
+
a.append("attachment", n, r), await this.client.request(o, t, {
|
|
360
361
|
method: "PUT",
|
|
361
362
|
body: a,
|
|
362
363
|
isFormData: !0
|
|
363
364
|
});
|
|
364
|
-
} catch (
|
|
365
|
-
if (l(
|
|
365
|
+
} catch (o) {
|
|
366
|
+
if (l(o))
|
|
366
367
|
return;
|
|
367
|
-
throw
|
|
368
|
+
throw o;
|
|
368
369
|
}
|
|
369
370
|
}
|
|
370
371
|
async createConversation(e, n) {
|
|
371
|
-
const t = e?.id || k(e), { name:
|
|
372
|
+
const t = e?.id || k(e), { name: o, folderId: a, model: r, messages: c, custom_fields: i } = e, u = {
|
|
372
373
|
id: t,
|
|
373
|
-
name:
|
|
374
|
+
name: o,
|
|
374
375
|
folderId: a,
|
|
375
|
-
model:
|
|
376
|
+
model: r,
|
|
376
377
|
messages: c || [],
|
|
377
378
|
selectedAddons: e.selectedAddons || [],
|
|
378
379
|
prompt: e.prompt || "",
|
|
@@ -390,9 +391,9 @@ class ot {
|
|
|
390
391
|
}
|
|
391
392
|
), {
|
|
392
393
|
id: t,
|
|
393
|
-
name:
|
|
394
|
+
name: o,
|
|
394
395
|
folderId: a,
|
|
395
|
-
model:
|
|
396
|
+
model: r,
|
|
396
397
|
createdAt: u.createdAt,
|
|
397
398
|
updatedAt: u.updatedAt
|
|
398
399
|
};
|
|
@@ -425,11 +426,11 @@ class ot {
|
|
|
425
426
|
);
|
|
426
427
|
}
|
|
427
428
|
async updateConversation(e, n, t) {
|
|
428
|
-
const
|
|
429
|
-
if (!
|
|
429
|
+
const o = await this.getConversation(e, t);
|
|
430
|
+
if (!o)
|
|
430
431
|
throw new Error(`Conversation with id ${e} not found`);
|
|
431
432
|
const a = {
|
|
432
|
-
...
|
|
433
|
+
...o,
|
|
433
434
|
...n,
|
|
434
435
|
updatedAt: Date.now()
|
|
435
436
|
};
|
|
@@ -460,7 +461,7 @@ class ot {
|
|
|
460
461
|
});
|
|
461
462
|
}
|
|
462
463
|
async streamChat(e, n) {
|
|
463
|
-
const t = e.model.id,
|
|
464
|
+
const t = e.model.id, o = encodeURIComponent(t), a = `${d.CHAT(o)}?api-version=${this.client.config.version}`, r = {
|
|
464
465
|
messages: e.messages,
|
|
465
466
|
stream: !0,
|
|
466
467
|
temperature: 0.7,
|
|
@@ -469,14 +470,14 @@ class ot {
|
|
|
469
470
|
};
|
|
470
471
|
return await this.client.stream(a, n, {
|
|
471
472
|
method: "POST",
|
|
472
|
-
body:
|
|
473
|
+
body: r,
|
|
473
474
|
chatReference: e.conversationId
|
|
474
475
|
});
|
|
475
476
|
}
|
|
476
|
-
async rateResponse(e, n, t,
|
|
477
|
+
async rateResponse(e, n, t, o) {
|
|
477
478
|
return await this.client.postRequest(
|
|
478
479
|
d.RATE(e),
|
|
479
|
-
|
|
480
|
+
o,
|
|
480
481
|
{
|
|
481
482
|
body: {
|
|
482
483
|
responseId: n,
|
|
@@ -510,7 +511,7 @@ class at {
|
|
|
510
511
|
return this.request(e, n, { ...t, method: "POST" });
|
|
511
512
|
}
|
|
512
513
|
async requestBlob(e, n, t) {
|
|
513
|
-
const
|
|
514
|
+
const o = `${this.config.host}${e}`, a = {
|
|
514
515
|
..._(this.config.apiKey, {
|
|
515
516
|
jwt: n,
|
|
516
517
|
chatReference: t.chatReference,
|
|
@@ -519,17 +520,17 @@ class at {
|
|
|
519
520
|
...t.headers
|
|
520
521
|
};
|
|
521
522
|
try {
|
|
522
|
-
return (await
|
|
523
|
-
} catch (
|
|
523
|
+
return (await T(o, a, t)).blob();
|
|
524
|
+
} catch (r) {
|
|
524
525
|
throw console.error("API Request Exception", {
|
|
525
526
|
method: t.method,
|
|
526
|
-
url:
|
|
527
|
-
error:
|
|
528
|
-
}),
|
|
527
|
+
url: o,
|
|
528
|
+
error: r instanceof Error ? r.message : String(r)
|
|
529
|
+
}), r;
|
|
529
530
|
}
|
|
530
531
|
}
|
|
531
532
|
async request(e, n, t) {
|
|
532
|
-
const
|
|
533
|
+
const o = Date.now(), a = `${this.config.host}${e}`, r = {
|
|
533
534
|
..._(this.config.apiKey, {
|
|
534
535
|
jwt: n,
|
|
535
536
|
chatReference: t.chatReference,
|
|
@@ -537,9 +538,9 @@ class at {
|
|
|
537
538
|
}),
|
|
538
539
|
...t.headers
|
|
539
540
|
};
|
|
540
|
-
this.addInfoRequestLog("API Request", a, t,
|
|
541
|
+
this.addInfoRequestLog("API Request", a, t, r);
|
|
541
542
|
try {
|
|
542
|
-
const c = await
|
|
543
|
+
const c = await T(a, r, t), i = Date.now() - o;
|
|
543
544
|
let u;
|
|
544
545
|
const m = await c.text();
|
|
545
546
|
try {
|
|
@@ -564,7 +565,7 @@ class at {
|
|
|
564
565
|
}
|
|
565
566
|
return u;
|
|
566
567
|
} catch (c) {
|
|
567
|
-
const i = Date.now() -
|
|
568
|
+
const i = Date.now() - o;
|
|
568
569
|
throw console.error("API Request Exception", {
|
|
569
570
|
method: t.method,
|
|
570
571
|
url: a,
|
|
@@ -574,7 +575,7 @@ class at {
|
|
|
574
575
|
}
|
|
575
576
|
}
|
|
576
577
|
async stream(e, n, t) {
|
|
577
|
-
const
|
|
578
|
+
const o = `${this.config.host}${e}`, a = _(
|
|
578
579
|
this.config.apiKey,
|
|
579
580
|
{
|
|
580
581
|
jwt: n,
|
|
@@ -583,46 +584,46 @@ class at {
|
|
|
583
584
|
},
|
|
584
585
|
t.headers
|
|
585
586
|
);
|
|
586
|
-
this.addInfoRequestLog("Stream Request",
|
|
587
|
-
const
|
|
588
|
-
if (!
|
|
587
|
+
this.addInfoRequestLog("Stream Request", o, t, a);
|
|
588
|
+
const r = await T(o, a, t);
|
|
589
|
+
if (!r.ok)
|
|
589
590
|
throw console.error("Stream Request Failed", {
|
|
590
591
|
method: t.method || "POST",
|
|
591
|
-
url:
|
|
592
|
-
status:
|
|
593
|
-
statusText:
|
|
592
|
+
url: o,
|
|
593
|
+
status: r.status,
|
|
594
|
+
statusText: r.statusText
|
|
594
595
|
}), new Error(
|
|
595
|
-
`Stream request failed: ${
|
|
596
|
+
`Stream request failed: ${r.status} ${r.statusText}`
|
|
596
597
|
);
|
|
597
|
-
if (!
|
|
598
|
+
if (!r.body)
|
|
598
599
|
throw new Error("No response body for stream");
|
|
599
|
-
return
|
|
600
|
+
return r.body;
|
|
600
601
|
}
|
|
601
|
-
addInfoRequestLog(e, n, t,
|
|
602
|
+
addInfoRequestLog(e, n, t, o) {
|
|
602
603
|
const a = {
|
|
603
604
|
method: t.method || "GET",
|
|
604
605
|
url: n,
|
|
605
|
-
headers: F(
|
|
606
|
+
headers: F(o)
|
|
606
607
|
};
|
|
607
608
|
t.body && (a.body = t.body), console.info(e, a);
|
|
608
609
|
}
|
|
609
|
-
addErrorRequestLog(e, n, t,
|
|
610
|
+
addErrorRequestLog(e, n, t, o, a) {
|
|
610
611
|
console.error("API Request Failed", {
|
|
611
612
|
method: n.method,
|
|
612
613
|
url: e,
|
|
613
614
|
status: t.status,
|
|
614
615
|
statusText: t.statusText,
|
|
615
|
-
duration: `${
|
|
616
|
+
duration: `${o}ms`,
|
|
616
617
|
response: a
|
|
617
618
|
});
|
|
618
619
|
}
|
|
619
|
-
addErrorRequestParsing(e, n, t,
|
|
620
|
+
addErrorRequestParsing(e, n, t, o, a) {
|
|
620
621
|
console.error("API Response Parse Error", {
|
|
621
622
|
method: n.method,
|
|
622
623
|
url: e,
|
|
623
624
|
status: t.status,
|
|
624
625
|
statusText: t.statusText,
|
|
625
|
-
duration: `${
|
|
626
|
+
duration: `${o}ms`,
|
|
626
627
|
responseText: a.substring(0, 200),
|
|
627
628
|
// First 200 chars
|
|
628
629
|
error: "Response is not valid JSON"
|
|
@@ -634,17 +635,17 @@ export {
|
|
|
634
635
|
J as COMPLETION_FINISH_REASON,
|
|
635
636
|
Q as CUSTOM_VIEW_STATE_KEY,
|
|
636
637
|
B as ChatStreamSSEClient,
|
|
637
|
-
|
|
638
|
+
rt as ConversationApi,
|
|
638
639
|
d as DIAL_API_ROUTES,
|
|
639
640
|
z as DIAL_ERROR_CODES,
|
|
640
641
|
W as DIAL_ERROR_TYPES,
|
|
641
642
|
at as DialApiClient,
|
|
642
|
-
|
|
643
|
+
y as ERROR_CONTEXT_KIND,
|
|
643
644
|
R as EXCEEDED_LIMIT,
|
|
644
645
|
X as EXCEEDED_LIMIT_ORDER,
|
|
645
646
|
$ as InvitationType,
|
|
646
647
|
A as ResourceTypes,
|
|
647
|
-
|
|
648
|
+
C as ShareTarget,
|
|
648
649
|
G as chatStreamSSEClient,
|
|
649
650
|
et as decodeApiUrl,
|
|
650
651
|
E as encodeApiUrl,
|
|
@@ -657,6 +658,6 @@ export {
|
|
|
657
658
|
nt as isRateLimitStillActive,
|
|
658
659
|
Z as mergeMessages,
|
|
659
660
|
j as parseConversationName,
|
|
660
|
-
|
|
661
|
-
|
|
661
|
+
T as sendRequest,
|
|
662
|
+
ot as streamChatResponse
|
|
662
663
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@epam/statgpt-dial-toolkit",
|
|
3
|
-
"version": "0.5.0-rc.
|
|
3
|
+
"version": "0.5.0-rc.15",
|
|
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.5.0-rc.
|
|
17
|
+
"@epam/statgpt-shared-toolkit": "0.5.0-rc.15",
|
|
18
18
|
"@epam/ai-dial-shared": "^0.43.3"
|
|
19
19
|
}
|
|
20
20
|
}
|