@epam/statgpt-dial-toolkit 0.5.0-rc.9 → 0.5.0
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 +3 -3
- package/index.mjs +349 -338
- package/models/chat-stream.d.ts +1 -0
- 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",
|
|
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
|
|
3
|
-
`);return await this.client.request(
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l="v1",T=`/${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:`${T}/create`,SHARE_CONVERSATION_ACCEPT:s=>`/${l}/invitations/${s}?accept=true`,SHARE_CONVERSATION_DETAILS:s=>`/${l}/invitations/${s}`,SHARE_CONVERSATION_LIST:`${T}/list`,SHARE_CONVERSATION_DISCARD:`${T}/discard`,SHARE_CONVERSATION_REVOKE:`${T}/revoke`,RATE:s=>`/${l}/${s}/rate`,RENAME:`/${l}/ops/resource/move`},U={LENGTH:"length",STOP:"stop"},f={MINUTE:"minute",DAILY:"daily",WEEKLY:"weekly",MONTHLY:"monthly"},V={CONTENT_FILTER:"content_filter",500:"500"},x={RUNTIME_ERROR:"runtime_error",RATE_LIMIT_EXCEEDED:"rate_limit_exceeded"},F=[f.MINUTE,f.DAILY,f.WEEKLY,f.MONTHLY],K="statgpt",g={RATE_LIMIT:"rate_limit",UNKNOWN:"unknown"};var C=(s=>(s.CONVERSATION="CONVERSATION",s))(C||{}),y=(s=>(s.ME="me",s.OTHERS="others",s))(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))($||{}),D=(s=>(s.LINK="link",s))(D||{});const j=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),v=(s,t,n)=>{if(t?.(s),n){const e=j(s);e&&n(e)}},w=(s,t)=>s.error||s.message||`${t.status} ${t.statusText}`,k=(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)},Y=(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&&B(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=k(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 B(s,t){if(t.content){const n=G(t.content);n!=null?s.content=s.content.slice(0,-n):s.content=`${s.content||""}${t.content}`}}function G(s){const t=s.match(/delete_chars\((\d+)\)/);return t!=null?parseInt(t[1],10):null}const J={CHAT:"/api/chat"},X="application/json",z="Content-Type",p="Api-Key",W="X-CONVERSATION-ID",O="Ocp-Apim-Subscription-Key";class N 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 Q=s=>new RegExp("\\p{L}","u").test(s)||new RegExp("\\p{N}","u").test(s),Z=s=>{if(!s)return"";const t=s.toLowerCase(),n=[];let e="";for(const r of t)Q(r)?e+=r:e&&(n.push(e),e="");return e&&n.push(e),n.join(" ")},A=(s,t,n)=>{const e={};return t?.contentType!==null&&(e[z]=t?.contentType||X),t?.jwt?e.Authorization=`Bearer ${t.jwt}`:s&&(e[p]=s),t?.chatReference&&(e[W]=t.chatReference),{...e,...n}},ee=s=>{const t={...s};return t[p]&&(t[p]=t[p].substring(0,8)+"...[REDACTED]"),t.Authorization&&(t.Authorization="Bearer [REDACTED]"),t[O]&&(t[O]=t[O].substring(0,8)+"...[REDACTED]"),t},te=s=>({"Content-Type":`multipart/form-data; boundary=${s}`}),L=s=>{const t=s.name?.split("__")||[],n=t.length>1?t.slice(1).join("__"):s.name;return{modelId:t[0],conversationName:n}},b=s=>{const t=Date.now(),n=Z(s.name);return`${s.folderId}/${n}-${t}`},ne=s=>({resourceTypes:[C.CONVERSATION],with:s}),_=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 h(s){return s.split("/").map(t=>encodeURIComponent(t)).join("/")}function se(s){return s.split("/").map(t=>decodeURIComponent(t)).join("/")}function q(s){if(s?.kind!==g.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 re(s,t=Date.now()){const n=q(s);return n?n.getTime()>t:!1}function oe(s,t="en-GB"){return{date:s.toLocaleDateString(t),time:s.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}}class M{constructor(){this.decoder=new TextDecoder}async streamChat(t,n,e={},r){const{onMessage:o,onError:a,onComplete:i,signal:c}=e;try{const u=await this.initializeStreamRequest(t,n,c,r);await this.processStreamData(u,o),i?.()}catch(u){this.handleStreamError(u,a)}}async initializeStreamRequest(t,n,e,r){const o=A(void 0,{jwt:r}),a=await _(t,{Accept:"text/event-stream",...o},{method:"POST",body:n,signal:e});if(!a.ok){const i=await a.text();let c={};try{c=JSON.parse(i)}catch{c.error="Failed to parse error body"}throw new N({status:a.status,message:c.error??"No response body"})}if(!a.body)throw new N({message:"No response body",status:a.status});return a.body.getReader()}async processStreamData(t,n){let e="";try{for(;;){const{done:r,value:o}=await t.read();if(r){e.trim()&&this.parseSSEDataLine(e,n);break}const a=this.decoder.decode(o,{stream:!0});e+=a;const i=e.split(`
|
|
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 o;try{o=JSON.parse(r)}catch(a){console.error(`Failed to parse SSE data: ${r} ${a}`)}n?.(o)}}}const H=new M,ae=async(s,t,n,e,r)=>{const{onMessage:o,onToken:a,onComplete:i,onError:c,model:u,signal:R}=n,I={conversationId:s,messages:t,model:u,custom_fields:r};await H.streamChat(J.CHAT,I,{onMessage:P=>v(P,o,a),onComplete:i,onError:c,signal:R},e)},m=s=>s instanceof Error&&s.message.includes("404"),S=s=>`/v1/conversations/${h(s)}`;function E(s){console.warn("[ConversationApi] suppressed error, returning empty result",s)}class ie{constructor(t){this.client=t}async getConversations(t,n,e){const r=`${n?e?`${n}/${e}`:`${n}`:""}`,o=`${d.CONVERSATIONS}/${r}`;try{return(await this.client.getRequest(o+"/?limit=1000&recursive=false",t).then(i=>i.items||[])).map(i=>{const{conversationName:c,modelId:u}=L(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(a){if(m(a))return E({endpoint:o,error:a}),[];throw a}}async getConversation(t,n){try{return await this.client.getRequest(S(t),n)}catch(e){if(m(e))return E({endpoint:S(t),error:e}),null;throw e}}async getFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async putOnboardingFile(t,n,e,r){try{const o=`${d.VERSION}/${h(n)}`,a="----NodeMultipartBoundary",c=[`--${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,r,{method:"PUT",body:c,headers:te(a),isFormData:!0})}catch(o){if(m(o))return E({filePath:n,error:o}),null;throw o}}async getOnboardingFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.getRequest(e,n)}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async getFileBlob(t,n){try{const e=`${d.VERSION}/${h(t)}`;return await this.client.requestBlob(e,n,{method:"GET"})}catch(e){if(m(e))return E({filePath:t,error:e}),null;throw e}}async deleteFile(t,n){try{const e=`${d.VERSION}/${h(t)}`;await this.client.request(e,n,{method:"DELETE"})}catch(e){if(m(e)){E({filePath:t,error:e});return}throw e}}async putFile(t,n,e){try{const r=`${d.VERSION}/${h(t)}`,o=new FormData,a=decodeURIComponent(t.split("/").at(-1)??"file");o.append("attachment",n,a),await this.client.request(r,e,{method:"PUT",body:o,isFormData:!0})}catch(r){if(m(r)){E({filePath:t,error:r});return}throw r}}async createConversation(t,n){const e=t?.id||b(t),{name:r,folderId:o,model:a,messages:i,custom_fields:c}=t,u={id:e,name:r,folderId:o,model:a,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(S(e),n,{method:"PUT",body:u}),{id:e,name:r,folderId:o,model:a,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 o={...r,...n,updatedAt:Date.now()};return await this.client.request(S(t),e,{method:"PUT",body:o})}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(S(decodeURI(t)),e,{method:"DELETE"})}async streamChat(t,n){const e=t.model.id,r=encodeURIComponent(e),o=`${d.CHAT(r)}?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,n,{method:"POST",body:a,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 ce{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}`,o={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};try{return(await _(r,o,e)).blob()}catch(a){throw console.error("API Request Exception",{method:e.method,url:r,error:a instanceof Error?a.message:String(a)}),a}}async request(t,n,e){const r=Date.now(),o=`${this.config.host}${t}`,a={...A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0}),...e.headers};this.addInfoRequestLog("API Request",o,e,a);try{const i=await _(o,a,e),c=Date.now()-r;let u;const R=await i.text();try{u=R?JSON.parse(R):{}}catch{if(this.addErrorRequestParsing(o,e,i,c,R),!i.ok)throw new Error(`API request failed: ${i.status} ${i.statusText} - ${R.substring(0,100)}`);u={data:R}}if(!i.ok){this.addErrorRequestLog(o,e,i,c,u);const I=w(u,i);throw new Error(`API request failed: ${I}`)}return u}catch(i){const c=Date.now()-r;throw console.error("API Request Exception",{method:e.method,url:o,duration:`${c}ms`,error:i instanceof Error?i.message:String(i)}),i}}async stream(t,n,e){const r=`${this.config.host}${t}`,o=A(this.config.apiKey,{jwt:n,chatReference:e.chatReference,contentType:e.isFormData?null:void 0},e.headers);this.addInfoRequestLog("Stream Request",r,e,o);const a=await _(r,o,e);if(!a.ok)throw console.error("Stream Request Failed",{method:e.method||"POST",url:r,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,n,e,r){const o={method:e.method||"GET",url:n,headers:ee(r)};e.body&&(o.body=e.body),console.info(t,o)}addErrorRequestLog(t,n,e,r,o){console.error("API Request Failed",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,response:o})}addErrorRequestParsing(t,n,e,r,o){console.error("API Response Parse Error",{method:n.method,url:t,status:e.status,statusText:e.statusText,duration:`${r}ms`,responseText:o.substring(0,200),error:"Response is not valid JSON"})}}exports.AttachmentType=$;exports.COMPLETION_FINISH_REASON=U;exports.CUSTOM_VIEW_STATE_KEY=K;exports.ChatStreamSSEClient=M;exports.ConversationApi=ie;exports.DIAL_API_ROUTES=d;exports.DIAL_ERROR_CODES=V;exports.DIAL_ERROR_TYPES=x;exports.DialApiClient=ce;exports.ERROR_CONTEXT_KIND=g;exports.EXCEEDED_LIMIT=f;exports.EXCEEDED_LIMIT_ORDER=F;exports.InvitationType=D;exports.ResourceTypes=C;exports.ShareTarget=y;exports.chatStreamSSEClient=H;exports.decodeApiUrl=se;exports.encodeApiUrl=h;exports.formatDateTime=oe;exports.generateConversationId=b;exports.getErrorMessage=w;exports.getRateLimitRestoreDate=q;exports.getSharedConversationsRequest=ne;exports.handleStreamMessage=v;exports.isRateLimitStillActive=re;exports.mergeMessages=Y;exports.parseConversationName=L;exports.sendRequest=_;exports.streamChatResponse=ae;
|
package/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const
|
|
1
|
+
const f = "/v1/ops/resource/share", d = {
|
|
2
2
|
VERSION: "/v1",
|
|
3
3
|
BUCKET: "/v1/bucket",
|
|
4
4
|
CONVERSATIONS: "/v1/metadata/conversations",
|
|
@@ -7,445 +7,456 @@ 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
|
-
|
|
10
|
+
PYTHON_ATTACHMENT: (s) => `/v1/deployments/${s}/route/python-attachment`,
|
|
11
|
+
SHARE_CONVERSATION: `${f}/create`,
|
|
11
12
|
SHARE_CONVERSATION_ACCEPT: (s) => `/v1/invitations/${s}?accept=true`,
|
|
12
13
|
SHARE_CONVERSATION_DETAILS: (s) => `/v1/invitations/${s}`,
|
|
13
|
-
SHARE_CONVERSATION_LIST: `${
|
|
14
|
-
SHARE_CONVERSATION_DISCARD: `${
|
|
15
|
-
SHARE_CONVERSATION_REVOKE: `${
|
|
14
|
+
SHARE_CONVERSATION_LIST: `${f}/list`,
|
|
15
|
+
SHARE_CONVERSATION_DISCARD: `${f}/discard`,
|
|
16
|
+
SHARE_CONVERSATION_REVOKE: `${f}/revoke`,
|
|
16
17
|
RATE: (s) => `/v1/${s}/rate`,
|
|
17
18
|
RENAME: "/v1/ops/resource/move"
|
|
18
|
-
},
|
|
19
|
+
}, z = {
|
|
19
20
|
LENGTH: "length",
|
|
20
21
|
STOP: "stop"
|
|
21
|
-
},
|
|
22
|
+
}, S = {
|
|
22
23
|
MINUTE: "minute",
|
|
23
24
|
DAILY: "daily",
|
|
24
25
|
WEEKLY: "weekly",
|
|
25
26
|
MONTHLY: "monthly"
|
|
26
|
-
},
|
|
27
|
+
}, W = {
|
|
27
28
|
CONTENT_FILTER: "content_filter",
|
|
28
29
|
500: "500"
|
|
29
|
-
},
|
|
30
|
+
}, X = {
|
|
30
31
|
RUNTIME_ERROR: "runtime_error",
|
|
31
32
|
RATE_LIMIT_EXCEEDED: "rate_limit_exceeded"
|
|
32
|
-
},
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
],
|
|
33
|
+
}, Q = [
|
|
34
|
+
S.MINUTE,
|
|
35
|
+
S.DAILY,
|
|
36
|
+
S.WEEKLY,
|
|
37
|
+
S.MONTHLY
|
|
38
|
+
], Z = "statgpt", C = {
|
|
38
39
|
RATE_LIMIT: "rate_limit",
|
|
39
40
|
UNKNOWN: "unknown"
|
|
40
41
|
};
|
|
41
|
-
var
|
|
42
|
-
const
|
|
42
|
+
var N = /* @__PURE__ */ ((s) => (s.CONVERSATION = "CONVERSATION", s))(N || {}), g = /* @__PURE__ */ ((s) => (s.ME = "me", s.OTHERS = "others", s))(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))($ || {}), w = /* @__PURE__ */ ((s) => (s.LINK = "link", s))(w || {});
|
|
43
|
+
const v = (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
|
-
), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null),
|
|
45
|
-
if (
|
|
46
|
-
const
|
|
47
|
-
|
|
45
|
+
), s.choices[0].message.content) : (console.info("Unknown SSE data format:", s), null), D = (s, t, n) => {
|
|
46
|
+
if (t?.(s), n) {
|
|
47
|
+
const e = v(s);
|
|
48
|
+
e && n(e);
|
|
48
49
|
}
|
|
49
|
-
},
|
|
50
|
+
}, b = (s, t) => s.error || s.message || `${t.status} ${t.statusText}`, q = (s, t) => {
|
|
50
51
|
const n = s?.reduce(
|
|
51
|
-
(
|
|
52
|
+
(e, r) => (e[r.index] = r, e),
|
|
52
53
|
{}
|
|
53
54
|
);
|
|
54
|
-
return
|
|
55
|
-
n[
|
|
55
|
+
return t.forEach((e) => {
|
|
56
|
+
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;
|
|
56
57
|
}), Object.values(n);
|
|
57
|
-
},
|
|
58
|
+
}, ee = (s, t) => {
|
|
58
59
|
const n = structuredClone(s);
|
|
59
|
-
return
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
)),
|
|
60
|
+
return t.forEach((e) => {
|
|
61
|
+
e.errorMessage && (n.errorMessage = e.errorMessage), e.role && (n.role = e.role), e.responseId && (n.responseId = e.responseId), e.content && L(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(
|
|
62
|
+
e.custom_content.attachments
|
|
63
|
+
)), e.custom_content.stages && (n.custom_content.stages || (n.custom_content.stages = []), n.custom_content.stages = q(
|
|
63
64
|
n.custom_content.stages,
|
|
64
|
-
|
|
65
|
-
)),
|
|
65
|
+
e.custom_content.stages
|
|
66
|
+
)), 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));
|
|
66
67
|
}), n;
|
|
67
68
|
};
|
|
68
|
-
function
|
|
69
|
-
if (
|
|
70
|
-
const n =
|
|
71
|
-
n != null ? s.content = s.content.slice(0, -n) : s.content = `${s.content || ""}${
|
|
69
|
+
function L(s, t) {
|
|
70
|
+
if (t.content) {
|
|
71
|
+
const n = V(t.content);
|
|
72
|
+
n != null ? s.content = s.content.slice(0, -n) : s.content = `${s.content || ""}${t.content}`;
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
|
-
function
|
|
75
|
-
const
|
|
76
|
-
return
|
|
75
|
+
function V(s) {
|
|
76
|
+
const t = s.match(/delete_chars\((\d+)\)/);
|
|
77
|
+
return t != null ? parseInt(t[1], 10) : null;
|
|
77
78
|
}
|
|
78
|
-
const
|
|
79
|
+
const M = {
|
|
79
80
|
CHAT: "/api/chat"
|
|
80
|
-
},
|
|
81
|
-
class
|
|
82
|
-
constructor(
|
|
83
|
-
super(
|
|
81
|
+
}, H = "application/json", x = "Content-Type", p = "Api-Key", P = "X-CONVERSATION-ID", I = "Ocp-Apim-Subscription-Key";
|
|
82
|
+
class A extends Error {
|
|
83
|
+
constructor(t) {
|
|
84
|
+
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;
|
|
84
85
|
}
|
|
85
86
|
}
|
|
86
|
-
const
|
|
87
|
+
const U = (s) => new RegExp("\\p{L}", "u").test(s) || new RegExp("\\p{N}", "u").test(s), F = (s) => {
|
|
87
88
|
if (!s) return "";
|
|
88
|
-
const
|
|
89
|
-
let
|
|
90
|
-
for (const r of
|
|
91
|
-
|
|
92
|
-
return
|
|
93
|
-
}, _ = (s,
|
|
94
|
-
const
|
|
95
|
-
return
|
|
96
|
-
},
|
|
97
|
-
const
|
|
98
|
-
return
|
|
99
|
-
},
|
|
89
|
+
const t = s.toLowerCase(), n = [];
|
|
90
|
+
let e = "";
|
|
91
|
+
for (const r of t)
|
|
92
|
+
U(r) ? e += r : e && (n.push(e), e = "");
|
|
93
|
+
return e && n.push(e), n.join(" ");
|
|
94
|
+
}, _ = (s, t, n) => {
|
|
95
|
+
const e = {};
|
|
96
|
+
return t?.contentType !== null && (e[x] = t?.contentType || H), t?.jwt ? e.Authorization = `Bearer ${t.jwt}` : s && (e[p] = s), t?.chatReference && (e[P] = t.chatReference), { ...e, ...n };
|
|
97
|
+
}, K = (s) => {
|
|
98
|
+
const t = { ...s };
|
|
99
|
+
return t[p] && (t[p] = t[p].substring(0, 8) + "...[REDACTED]"), t.Authorization && (t.Authorization = "Bearer [REDACTED]"), t[I] && (t[I] = t[I].substring(0, 8) + "...[REDACTED]"), t;
|
|
100
|
+
}, j = (s) => ({
|
|
100
101
|
"Content-Type": `multipart/form-data; boundary=${s}`
|
|
101
|
-
}),
|
|
102
|
-
const
|
|
103
|
-
return { modelId:
|
|
104
|
-
},
|
|
105
|
-
const
|
|
106
|
-
return `${s.folderId}/${n}-${
|
|
107
|
-
},
|
|
108
|
-
const
|
|
102
|
+
}), k = (s) => {
|
|
103
|
+
const t = s.name?.split("__") || [], n = t.length > 1 ? t.slice(1).join("__") : s.name;
|
|
104
|
+
return { modelId: t[0], conversationName: n };
|
|
105
|
+
}, Y = (s) => {
|
|
106
|
+
const t = Date.now(), n = F(s.name);
|
|
107
|
+
return `${s.folderId}/${n}-${t}`;
|
|
108
|
+
}, te = (s) => ({ resourceTypes: [N.CONVERSATION], with: s }), T = async (s, t, n) => {
|
|
109
|
+
const e = 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",
|
|
111
|
-
headers:
|
|
112
|
-
body:
|
|
112
|
+
headers: t,
|
|
113
|
+
body: e,
|
|
113
114
|
signal: n?.signal
|
|
114
115
|
});
|
|
115
116
|
};
|
|
116
|
-
function
|
|
117
|
-
return s.split("/").map((
|
|
117
|
+
function h(s) {
|
|
118
|
+
return s.split("/").map((t) => encodeURIComponent(t)).join("/");
|
|
118
119
|
}
|
|
119
|
-
function
|
|
120
|
-
return s.split("/").map((
|
|
120
|
+
function ne(s) {
|
|
121
|
+
return s.split("/").map((t) => decodeURIComponent(t)).join("/");
|
|
121
122
|
}
|
|
122
|
-
function
|
|
123
|
+
function B(s) {
|
|
123
124
|
if (s?.kind !== C.RATE_LIMIT || typeof s.retryAfterSeconds != "number")
|
|
124
125
|
return null;
|
|
125
|
-
const
|
|
126
|
-
return Number.isNaN(
|
|
126
|
+
const t = new Date(s.occurredAt).getTime();
|
|
127
|
+
return Number.isNaN(t) ? null : new Date(t + s.retryAfterSeconds * 1e3);
|
|
127
128
|
}
|
|
128
|
-
function
|
|
129
|
-
const n =
|
|
130
|
-
return n ? n.getTime() >
|
|
129
|
+
function se(s, t = Date.now()) {
|
|
130
|
+
const n = B(s);
|
|
131
|
+
return n ? n.getTime() > t : !1;
|
|
131
132
|
}
|
|
132
|
-
function
|
|
133
|
+
function re(s, t = "en-GB") {
|
|
133
134
|
return {
|
|
134
|
-
date: s.toLocaleDateString(
|
|
135
|
-
time: s.toLocaleTimeString(
|
|
135
|
+
date: s.toLocaleDateString(t),
|
|
136
|
+
time: s.toLocaleTimeString(t, {
|
|
136
137
|
hour: "2-digit",
|
|
137
138
|
minute: "2-digit"
|
|
138
139
|
})
|
|
139
140
|
};
|
|
140
141
|
}
|
|
141
|
-
class
|
|
142
|
+
class G {
|
|
142
143
|
constructor() {
|
|
143
144
|
this.decoder = new TextDecoder();
|
|
144
145
|
}
|
|
145
|
-
async streamChat(
|
|
146
|
-
const { onMessage:
|
|
146
|
+
async streamChat(t, n, e = {}, r) {
|
|
147
|
+
const { onMessage: o, onError: c, onComplete: a, signal: i } = e;
|
|
147
148
|
try {
|
|
148
149
|
const u = await this.initializeStreamRequest(
|
|
149
|
-
|
|
150
|
+
t,
|
|
150
151
|
n,
|
|
151
152
|
i,
|
|
152
153
|
r
|
|
153
154
|
);
|
|
154
|
-
await this.processStreamData(u,
|
|
155
|
+
await this.processStreamData(u, o), a?.();
|
|
155
156
|
} catch (u) {
|
|
156
|
-
this.handleStreamError(u,
|
|
157
|
+
this.handleStreamError(u, c);
|
|
157
158
|
}
|
|
158
159
|
}
|
|
159
|
-
async initializeStreamRequest(
|
|
160
|
-
const
|
|
160
|
+
async initializeStreamRequest(t, n, e, r) {
|
|
161
|
+
const o = _(void 0, {
|
|
161
162
|
jwt: r
|
|
162
|
-
}),
|
|
163
|
-
|
|
163
|
+
}), c = await T(
|
|
164
|
+
t,
|
|
164
165
|
{
|
|
165
166
|
Accept: "text/event-stream",
|
|
166
|
-
...
|
|
167
|
+
...o
|
|
167
168
|
},
|
|
168
169
|
{
|
|
169
170
|
method: "POST",
|
|
170
171
|
body: n,
|
|
171
|
-
signal:
|
|
172
|
+
signal: e
|
|
172
173
|
}
|
|
173
174
|
);
|
|
174
|
-
if (!
|
|
175
|
-
const
|
|
175
|
+
if (!c.ok) {
|
|
176
|
+
const a = await c.text();
|
|
176
177
|
let i = {};
|
|
177
178
|
try {
|
|
178
|
-
i = JSON.parse(
|
|
179
|
+
i = JSON.parse(a);
|
|
179
180
|
} catch {
|
|
180
181
|
i.error = "Failed to parse error body";
|
|
181
182
|
}
|
|
182
|
-
throw new
|
|
183
|
-
status:
|
|
183
|
+
throw new A({
|
|
184
|
+
status: c.status,
|
|
184
185
|
message: i.error ?? "No response body"
|
|
185
186
|
});
|
|
186
187
|
}
|
|
187
|
-
if (!
|
|
188
|
-
throw new
|
|
188
|
+
if (!c.body)
|
|
189
|
+
throw new A({
|
|
189
190
|
message: "No response body",
|
|
190
|
-
status:
|
|
191
|
+
status: c.status
|
|
191
192
|
});
|
|
192
|
-
return
|
|
193
|
+
return c.body.getReader();
|
|
193
194
|
}
|
|
194
|
-
async processStreamData(
|
|
195
|
-
let
|
|
195
|
+
async processStreamData(t, n) {
|
|
196
|
+
let e = "";
|
|
196
197
|
try {
|
|
197
198
|
for (; ; ) {
|
|
198
|
-
const { done: r, value:
|
|
199
|
+
const { done: r, value: o } = await t.read();
|
|
199
200
|
if (r) {
|
|
200
|
-
|
|
201
|
+
e.trim() && this.parseSSEDataLine(e, n);
|
|
201
202
|
break;
|
|
202
203
|
}
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
const
|
|
204
|
+
const c = this.decoder.decode(o, { stream: !0 });
|
|
205
|
+
e += c;
|
|
206
|
+
const a = e.split(`
|
|
206
207
|
`);
|
|
207
|
-
|
|
208
|
-
for (const i of
|
|
208
|
+
e = a.pop() || "";
|
|
209
|
+
for (const i of a)
|
|
209
210
|
this.parseSSEDataLine(i, n);
|
|
210
211
|
}
|
|
211
212
|
} finally {
|
|
212
|
-
|
|
213
|
+
t.releaseLock();
|
|
213
214
|
}
|
|
214
215
|
}
|
|
215
|
-
handleStreamError(
|
|
216
|
-
const
|
|
217
|
-
throw n?.(
|
|
216
|
+
handleStreamError(t, n) {
|
|
217
|
+
const e = t instanceof Error ? t : new Error(String(t));
|
|
218
|
+
throw n?.(e), e;
|
|
218
219
|
}
|
|
219
|
-
parseSSEDataLine(
|
|
220
|
-
const
|
|
221
|
-
if (!(!
|
|
222
|
-
const r =
|
|
220
|
+
parseSSEDataLine(t, n) {
|
|
221
|
+
const e = t.trim();
|
|
222
|
+
if (!(!e || e.startsWith(":")) && e.startsWith("data: ")) {
|
|
223
|
+
const r = e.slice(6);
|
|
223
224
|
if (r === "[DONE]") {
|
|
224
225
|
console.info("SSE: Stream completed");
|
|
225
226
|
return;
|
|
226
227
|
}
|
|
227
|
-
let
|
|
228
|
+
let o;
|
|
228
229
|
try {
|
|
229
|
-
|
|
230
|
-
} catch (
|
|
231
|
-
console.error(`Failed to parse SSE data: ${r} ${
|
|
230
|
+
o = JSON.parse(r);
|
|
231
|
+
} catch (c) {
|
|
232
|
+
console.error(`Failed to parse SSE data: ${r} ${c}`);
|
|
232
233
|
}
|
|
233
|
-
n?.(
|
|
234
|
+
n?.(o);
|
|
234
235
|
}
|
|
235
236
|
}
|
|
236
237
|
}
|
|
237
|
-
const
|
|
238
|
-
const { onMessage:
|
|
238
|
+
const J = new G(), oe = async (s, t, n, e, r) => {
|
|
239
|
+
const { onMessage: o, onToken: c, onComplete: a, onError: i, model: u, signal: E } = n, O = {
|
|
239
240
|
conversationId: s,
|
|
240
|
-
messages:
|
|
241
|
+
messages: t,
|
|
241
242
|
model: u,
|
|
242
243
|
custom_fields: r
|
|
243
244
|
};
|
|
244
|
-
await
|
|
245
|
-
|
|
245
|
+
await J.streamChat(
|
|
246
|
+
M.CHAT,
|
|
246
247
|
O,
|
|
247
248
|
{
|
|
248
|
-
onMessage: (
|
|
249
|
-
onComplete:
|
|
249
|
+
onMessage: (y) => D(y, o, c),
|
|
250
|
+
onComplete: a,
|
|
250
251
|
onError: i,
|
|
251
|
-
signal:
|
|
252
|
+
signal: E
|
|
252
253
|
},
|
|
253
|
-
|
|
254
|
+
e
|
|
255
|
+
);
|
|
256
|
+
}, l = (s) => s instanceof Error && s.message.includes("404"), R = (s) => `/v1/conversations/${h(s)}`;
|
|
257
|
+
function m(s) {
|
|
258
|
+
console.warn(
|
|
259
|
+
"[ConversationApi] suppressed error, returning empty result",
|
|
260
|
+
s
|
|
254
261
|
);
|
|
255
|
-
}
|
|
256
|
-
class
|
|
257
|
-
constructor(
|
|
258
|
-
this.client =
|
|
262
|
+
}
|
|
263
|
+
class ce {
|
|
264
|
+
constructor(t) {
|
|
265
|
+
this.client = t;
|
|
259
266
|
}
|
|
260
|
-
async getConversations(
|
|
261
|
-
const r = `${n ?
|
|
267
|
+
async getConversations(t, n, e) {
|
|
268
|
+
const r = `${n ? e ? `${n}/${e}` : `${n}` : ""}`, o = `${d.CONVERSATIONS}/${r}`;
|
|
262
269
|
try {
|
|
263
|
-
return (await this.client.getRequest(
|
|
264
|
-
const { conversationName: i, modelId: u } =
|
|
270
|
+
return (await this.client.getRequest(o + "/?limit=1000&recursive=false", t).then((a) => a.items || [])).map((a) => {
|
|
271
|
+
const { conversationName: i, modelId: u } = k(a);
|
|
265
272
|
return {
|
|
266
|
-
id:
|
|
273
|
+
id: a.url?.replace("conversations/", "") || a.name,
|
|
267
274
|
name: i,
|
|
268
275
|
folderId: r,
|
|
269
|
-
createdAt:
|
|
270
|
-
updatedAt:
|
|
276
|
+
createdAt: a.createdAt,
|
|
277
|
+
updatedAt: a.updatedAt,
|
|
271
278
|
model: { id: u, name: u }
|
|
272
279
|
};
|
|
273
280
|
});
|
|
274
|
-
} catch (
|
|
275
|
-
if (l(
|
|
276
|
-
return [];
|
|
277
|
-
throw
|
|
281
|
+
} catch (c) {
|
|
282
|
+
if (l(c))
|
|
283
|
+
return m({ endpoint: o, error: c }), [];
|
|
284
|
+
throw c;
|
|
278
285
|
}
|
|
279
286
|
}
|
|
280
|
-
async getConversation(
|
|
287
|
+
async getConversation(t, n) {
|
|
281
288
|
try {
|
|
282
289
|
return await this.client.getRequest(
|
|
283
|
-
|
|
290
|
+
R(t),
|
|
284
291
|
n
|
|
285
292
|
);
|
|
286
|
-
} catch (
|
|
287
|
-
if (l(
|
|
288
|
-
return null;
|
|
289
|
-
throw
|
|
293
|
+
} catch (e) {
|
|
294
|
+
if (l(e))
|
|
295
|
+
return m({ endpoint: R(t), error: e }), null;
|
|
296
|
+
throw e;
|
|
290
297
|
}
|
|
291
298
|
}
|
|
292
|
-
async getFile(
|
|
299
|
+
async getFile(t, n) {
|
|
293
300
|
try {
|
|
294
|
-
const
|
|
295
|
-
return await this.client.getRequest(
|
|
296
|
-
} catch (
|
|
297
|
-
if (l(
|
|
298
|
-
return null;
|
|
299
|
-
throw
|
|
301
|
+
const e = `${d.VERSION}/${h(t)}`;
|
|
302
|
+
return await this.client.getRequest(e, n);
|
|
303
|
+
} catch (e) {
|
|
304
|
+
if (l(e))
|
|
305
|
+
return m({ filePath: t, error: e }), null;
|
|
306
|
+
throw e;
|
|
300
307
|
}
|
|
301
308
|
}
|
|
302
|
-
async putOnboardingFile(
|
|
309
|
+
async putOnboardingFile(t, n, e, r) {
|
|
303
310
|
try {
|
|
304
|
-
const
|
|
305
|
-
`--${
|
|
306
|
-
`Content-Disposition: form-data; name="file"; filename="${
|
|
311
|
+
const o = `${d.VERSION}/${h(n)}`, c = "----NodeMultipartBoundary", i = [
|
|
312
|
+
`--${c}`,
|
|
313
|
+
`Content-Disposition: form-data; name="file"; filename="${t}"`,
|
|
307
314
|
"Content-Type: application/json",
|
|
308
315
|
"",
|
|
309
|
-
JSON.stringify(
|
|
310
|
-
`--${
|
|
316
|
+
JSON.stringify(e),
|
|
317
|
+
`--${c}--`,
|
|
311
318
|
""
|
|
312
319
|
].join(`\r
|
|
313
320
|
`);
|
|
314
|
-
return await this.client.request(
|
|
321
|
+
return await this.client.request(o, r, {
|
|
315
322
|
method: "PUT",
|
|
316
323
|
body: i,
|
|
317
|
-
headers:
|
|
324
|
+
headers: j(c),
|
|
318
325
|
isFormData: !0
|
|
319
326
|
});
|
|
320
|
-
} catch (
|
|
321
|
-
if (l(
|
|
322
|
-
return null;
|
|
323
|
-
throw
|
|
327
|
+
} catch (o) {
|
|
328
|
+
if (l(o))
|
|
329
|
+
return m({ filePath: n, error: o }), null;
|
|
330
|
+
throw o;
|
|
324
331
|
}
|
|
325
332
|
}
|
|
326
|
-
async getOnboardingFile(
|
|
333
|
+
async getOnboardingFile(t, n) {
|
|
327
334
|
try {
|
|
328
|
-
const
|
|
329
|
-
return await this.client.getRequest(
|
|
330
|
-
} catch (
|
|
331
|
-
if (l(
|
|
332
|
-
return null;
|
|
333
|
-
throw
|
|
335
|
+
const e = `${d.VERSION}/${h(t)}`;
|
|
336
|
+
return await this.client.getRequest(e, n);
|
|
337
|
+
} catch (e) {
|
|
338
|
+
if (l(e))
|
|
339
|
+
return m({ filePath: t, error: e }), null;
|
|
340
|
+
throw e;
|
|
334
341
|
}
|
|
335
342
|
}
|
|
336
|
-
async getFileBlob(
|
|
343
|
+
async getFileBlob(t, n) {
|
|
337
344
|
try {
|
|
338
|
-
const
|
|
339
|
-
return await this.client.requestBlob(
|
|
340
|
-
} catch (
|
|
341
|
-
if (l(
|
|
342
|
-
return null;
|
|
343
|
-
throw
|
|
345
|
+
const e = `${d.VERSION}/${h(t)}`;
|
|
346
|
+
return await this.client.requestBlob(e, n, { method: "GET" });
|
|
347
|
+
} catch (e) {
|
|
348
|
+
if (l(e))
|
|
349
|
+
return m({ filePath: t, error: e }), null;
|
|
350
|
+
throw e;
|
|
344
351
|
}
|
|
345
352
|
}
|
|
346
|
-
async deleteFile(
|
|
353
|
+
async deleteFile(t, n) {
|
|
347
354
|
try {
|
|
348
|
-
const
|
|
349
|
-
await this.client.request(
|
|
350
|
-
} catch (
|
|
351
|
-
if (l(
|
|
355
|
+
const e = `${d.VERSION}/${h(t)}`;
|
|
356
|
+
await this.client.request(e, n, { method: "DELETE" });
|
|
357
|
+
} catch (e) {
|
|
358
|
+
if (l(e)) {
|
|
359
|
+
m({ filePath: t, error: e });
|
|
352
360
|
return;
|
|
353
|
-
|
|
361
|
+
}
|
|
362
|
+
throw e;
|
|
354
363
|
}
|
|
355
364
|
}
|
|
356
|
-
async putFile(
|
|
365
|
+
async putFile(t, n, e) {
|
|
357
366
|
try {
|
|
358
|
-
const r = `${d.VERSION}/${
|
|
359
|
-
|
|
367
|
+
const r = `${d.VERSION}/${h(t)}`, o = new FormData(), c = decodeURIComponent(t.split("/").at(-1) ?? "file");
|
|
368
|
+
o.append("attachment", n, c), await this.client.request(r, e, {
|
|
360
369
|
method: "PUT",
|
|
361
|
-
body:
|
|
370
|
+
body: o,
|
|
362
371
|
isFormData: !0
|
|
363
372
|
});
|
|
364
373
|
} catch (r) {
|
|
365
|
-
if (l(r))
|
|
374
|
+
if (l(r)) {
|
|
375
|
+
m({ filePath: t, error: r });
|
|
366
376
|
return;
|
|
377
|
+
}
|
|
367
378
|
throw r;
|
|
368
379
|
}
|
|
369
380
|
}
|
|
370
|
-
async createConversation(
|
|
371
|
-
const
|
|
372
|
-
id:
|
|
381
|
+
async createConversation(t, n) {
|
|
382
|
+
const e = t?.id || Y(t), { name: r, folderId: o, model: c, messages: a, custom_fields: i } = t, u = {
|
|
383
|
+
id: e,
|
|
373
384
|
name: r,
|
|
374
|
-
folderId:
|
|
375
|
-
model:
|
|
376
|
-
messages:
|
|
377
|
-
selectedAddons:
|
|
378
|
-
prompt:
|
|
379
|
-
temperature:
|
|
385
|
+
folderId: o,
|
|
386
|
+
model: c,
|
|
387
|
+
messages: a || [],
|
|
388
|
+
selectedAddons: t.selectedAddons || [],
|
|
389
|
+
prompt: t.prompt || "",
|
|
390
|
+
temperature: t.temperature || 0.7,
|
|
380
391
|
createdAt: Date.now(),
|
|
381
392
|
updatedAt: Date.now(),
|
|
382
393
|
custom_fields: i
|
|
383
394
|
};
|
|
384
395
|
return await this.client.request(
|
|
385
|
-
|
|
396
|
+
R(e),
|
|
386
397
|
n,
|
|
387
398
|
{
|
|
388
399
|
method: "PUT",
|
|
389
400
|
body: u
|
|
390
401
|
}
|
|
391
402
|
), {
|
|
392
|
-
id:
|
|
403
|
+
id: e,
|
|
393
404
|
name: r,
|
|
394
|
-
folderId:
|
|
395
|
-
model:
|
|
405
|
+
folderId: o,
|
|
406
|
+
model: c,
|
|
396
407
|
createdAt: u.createdAt,
|
|
397
408
|
updatedAt: u.updatedAt
|
|
398
409
|
};
|
|
399
410
|
}
|
|
400
|
-
async generateConversationLink(
|
|
411
|
+
async generateConversationLink(t, n) {
|
|
401
412
|
return await this.client.postRequest(
|
|
402
413
|
d.SHARE_CONVERSATION,
|
|
403
|
-
|
|
414
|
+
t,
|
|
404
415
|
{
|
|
405
416
|
body: n
|
|
406
417
|
}
|
|
407
418
|
);
|
|
408
419
|
}
|
|
409
|
-
async getSharedConversations(
|
|
420
|
+
async getSharedConversations(t, n) {
|
|
410
421
|
return await this.client.postRequest(
|
|
411
422
|
d.SHARE_CONVERSATION_LIST,
|
|
412
|
-
|
|
423
|
+
t,
|
|
413
424
|
{
|
|
414
425
|
body: n
|
|
415
426
|
}
|
|
416
427
|
);
|
|
417
428
|
}
|
|
418
|
-
async revokeSharedConversations(
|
|
429
|
+
async revokeSharedConversations(t, n) {
|
|
419
430
|
await this.client.postRequest(
|
|
420
431
|
d.SHARE_CONVERSATION_REVOKE,
|
|
421
|
-
|
|
432
|
+
t,
|
|
422
433
|
{
|
|
423
434
|
body: n
|
|
424
435
|
}
|
|
425
436
|
);
|
|
426
437
|
}
|
|
427
|
-
async updateConversation(
|
|
428
|
-
const r = await this.getConversation(
|
|
438
|
+
async updateConversation(t, n, e) {
|
|
439
|
+
const r = await this.getConversation(t, e);
|
|
429
440
|
if (!r)
|
|
430
|
-
throw new Error(`Conversation with id ${
|
|
431
|
-
const
|
|
441
|
+
throw new Error(`Conversation with id ${t} not found`);
|
|
442
|
+
const o = {
|
|
432
443
|
...r,
|
|
433
444
|
...n,
|
|
434
445
|
updatedAt: Date.now()
|
|
435
446
|
};
|
|
436
447
|
return await this.client.request(
|
|
437
|
-
|
|
438
|
-
|
|
448
|
+
R(t),
|
|
449
|
+
e,
|
|
439
450
|
{
|
|
440
451
|
method: "PUT",
|
|
441
|
-
body:
|
|
452
|
+
body: o
|
|
442
453
|
}
|
|
443
454
|
);
|
|
444
455
|
}
|
|
445
|
-
async deleteConversation(
|
|
456
|
+
async deleteConversation(t, n, e) {
|
|
446
457
|
n?.isShared ? await this.client.postRequest(
|
|
447
458
|
d.SHARE_CONVERSATION_DISCARD,
|
|
448
|
-
|
|
459
|
+
e,
|
|
449
460
|
{
|
|
450
461
|
body: {
|
|
451
462
|
resources: [
|
|
@@ -455,208 +466,208 @@ class ot {
|
|
|
455
466
|
]
|
|
456
467
|
}
|
|
457
468
|
}
|
|
458
|
-
) : await this.client.request(
|
|
469
|
+
) : await this.client.request(R(decodeURI(t)), e, {
|
|
459
470
|
method: "DELETE"
|
|
460
471
|
});
|
|
461
472
|
}
|
|
462
|
-
async streamChat(
|
|
463
|
-
const
|
|
464
|
-
messages:
|
|
473
|
+
async streamChat(t, n) {
|
|
474
|
+
const e = t.model.id, r = encodeURIComponent(e), o = `${d.CHAT(r)}?api-version=${this.client.config.version}`, c = {
|
|
475
|
+
messages: t.messages,
|
|
465
476
|
stream: !0,
|
|
466
477
|
temperature: 0.7,
|
|
467
478
|
max_tokens: 4096,
|
|
468
|
-
custom_fields:
|
|
479
|
+
custom_fields: t.custom_fields
|
|
469
480
|
};
|
|
470
|
-
return await this.client.stream(
|
|
481
|
+
return await this.client.stream(o, n, {
|
|
471
482
|
method: "POST",
|
|
472
|
-
body:
|
|
473
|
-
chatReference:
|
|
483
|
+
body: c,
|
|
484
|
+
chatReference: t.conversationId
|
|
474
485
|
});
|
|
475
486
|
}
|
|
476
|
-
async rateResponse(
|
|
487
|
+
async rateResponse(t, n, e, r) {
|
|
477
488
|
return await this.client.postRequest(
|
|
478
|
-
d.RATE(
|
|
489
|
+
d.RATE(t),
|
|
479
490
|
r,
|
|
480
491
|
{
|
|
481
492
|
body: {
|
|
482
493
|
responseId: n,
|
|
483
|
-
rate:
|
|
494
|
+
rate: e
|
|
484
495
|
}
|
|
485
496
|
}
|
|
486
497
|
);
|
|
487
498
|
}
|
|
488
|
-
async renameConversation(
|
|
489
|
-
return await this.client.postRequest(d.RENAME,
|
|
499
|
+
async renameConversation(t, n, e) {
|
|
500
|
+
return await this.client.postRequest(d.RENAME, e, {
|
|
490
501
|
body: {
|
|
491
|
-
sourceUrl:
|
|
502
|
+
sourceUrl: t,
|
|
492
503
|
destinationUrl: n,
|
|
493
504
|
overwrite: !0
|
|
494
505
|
}
|
|
495
506
|
});
|
|
496
507
|
}
|
|
497
508
|
}
|
|
498
|
-
class
|
|
499
|
-
constructor(
|
|
500
|
-
this.config =
|
|
501
|
-
host:
|
|
502
|
-
hasApiKey: !!
|
|
503
|
-
version:
|
|
509
|
+
class ae {
|
|
510
|
+
constructor(t) {
|
|
511
|
+
this.config = t, console.info("DialApiClient initialized", {
|
|
512
|
+
host: t.host || "NOT SET",
|
|
513
|
+
hasApiKey: !!t.apiKey,
|
|
514
|
+
version: t.version
|
|
504
515
|
});
|
|
505
516
|
}
|
|
506
|
-
async getRequest(
|
|
507
|
-
return this.request(
|
|
517
|
+
async getRequest(t, n, e) {
|
|
518
|
+
return this.request(t, n, { ...e, method: "GET" });
|
|
508
519
|
}
|
|
509
|
-
async postRequest(
|
|
510
|
-
return this.request(
|
|
520
|
+
async postRequest(t, n, e) {
|
|
521
|
+
return this.request(t, n, { ...e, method: "POST" });
|
|
511
522
|
}
|
|
512
|
-
async requestBlob(
|
|
513
|
-
const r = `${this.config.host}${
|
|
523
|
+
async requestBlob(t, n, e) {
|
|
524
|
+
const r = `${this.config.host}${t}`, o = {
|
|
514
525
|
..._(this.config.apiKey, {
|
|
515
526
|
jwt: n,
|
|
516
|
-
chatReference:
|
|
517
|
-
contentType:
|
|
527
|
+
chatReference: e.chatReference,
|
|
528
|
+
contentType: e.isFormData ? null : void 0
|
|
518
529
|
}),
|
|
519
|
-
...
|
|
530
|
+
...e.headers
|
|
520
531
|
};
|
|
521
532
|
try {
|
|
522
|
-
return (await
|
|
523
|
-
} catch (
|
|
533
|
+
return (await T(r, o, e)).blob();
|
|
534
|
+
} catch (c) {
|
|
524
535
|
throw console.error("API Request Exception", {
|
|
525
|
-
method:
|
|
536
|
+
method: e.method,
|
|
526
537
|
url: r,
|
|
527
|
-
error:
|
|
528
|
-
}),
|
|
538
|
+
error: c instanceof Error ? c.message : String(c)
|
|
539
|
+
}), c;
|
|
529
540
|
}
|
|
530
541
|
}
|
|
531
|
-
async request(
|
|
532
|
-
const r = Date.now(),
|
|
542
|
+
async request(t, n, e) {
|
|
543
|
+
const r = Date.now(), o = `${this.config.host}${t}`, c = {
|
|
533
544
|
..._(this.config.apiKey, {
|
|
534
545
|
jwt: n,
|
|
535
|
-
chatReference:
|
|
536
|
-
contentType:
|
|
546
|
+
chatReference: e.chatReference,
|
|
547
|
+
contentType: e.isFormData ? null : void 0
|
|
537
548
|
}),
|
|
538
|
-
...
|
|
549
|
+
...e.headers
|
|
539
550
|
};
|
|
540
|
-
this.addInfoRequestLog("API Request",
|
|
551
|
+
this.addInfoRequestLog("API Request", o, e, c);
|
|
541
552
|
try {
|
|
542
|
-
const
|
|
553
|
+
const a = await T(o, c, e), i = Date.now() - r;
|
|
543
554
|
let u;
|
|
544
|
-
const
|
|
555
|
+
const E = await a.text();
|
|
545
556
|
try {
|
|
546
|
-
u =
|
|
557
|
+
u = E ? JSON.parse(E) : {};
|
|
547
558
|
} catch {
|
|
548
559
|
if (this.addErrorRequestParsing(
|
|
560
|
+
o,
|
|
561
|
+
e,
|
|
549
562
|
a,
|
|
550
|
-
t,
|
|
551
|
-
c,
|
|
552
563
|
i,
|
|
553
|
-
|
|
554
|
-
), !
|
|
564
|
+
E
|
|
565
|
+
), !a.ok)
|
|
555
566
|
throw new Error(
|
|
556
|
-
`API request failed: ${
|
|
567
|
+
`API request failed: ${a.status} ${a.statusText} - ${E.substring(0, 100)}`
|
|
557
568
|
);
|
|
558
|
-
u = { data:
|
|
569
|
+
u = { data: E };
|
|
559
570
|
}
|
|
560
|
-
if (!
|
|
561
|
-
this.addErrorRequestLog(
|
|
562
|
-
const O =
|
|
571
|
+
if (!a.ok) {
|
|
572
|
+
this.addErrorRequestLog(o, e, a, i, u);
|
|
573
|
+
const O = b(u, a);
|
|
563
574
|
throw new Error(`API request failed: ${O}`);
|
|
564
575
|
}
|
|
565
576
|
return u;
|
|
566
|
-
} catch (
|
|
577
|
+
} catch (a) {
|
|
567
578
|
const i = Date.now() - r;
|
|
568
579
|
throw console.error("API Request Exception", {
|
|
569
|
-
method:
|
|
570
|
-
url:
|
|
580
|
+
method: e.method,
|
|
581
|
+
url: o,
|
|
571
582
|
duration: `${i}ms`,
|
|
572
|
-
error:
|
|
573
|
-
}),
|
|
583
|
+
error: a instanceof Error ? a.message : String(a)
|
|
584
|
+
}), a;
|
|
574
585
|
}
|
|
575
586
|
}
|
|
576
|
-
async stream(
|
|
577
|
-
const r = `${this.config.host}${
|
|
587
|
+
async stream(t, n, e) {
|
|
588
|
+
const r = `${this.config.host}${t}`, o = _(
|
|
578
589
|
this.config.apiKey,
|
|
579
590
|
{
|
|
580
591
|
jwt: n,
|
|
581
|
-
chatReference:
|
|
582
|
-
contentType:
|
|
592
|
+
chatReference: e.chatReference,
|
|
593
|
+
contentType: e.isFormData ? null : void 0
|
|
583
594
|
},
|
|
584
|
-
|
|
595
|
+
e.headers
|
|
585
596
|
);
|
|
586
|
-
this.addInfoRequestLog("Stream Request", r,
|
|
587
|
-
const
|
|
588
|
-
if (!
|
|
597
|
+
this.addInfoRequestLog("Stream Request", r, e, o);
|
|
598
|
+
const c = await T(r, o, e);
|
|
599
|
+
if (!c.ok)
|
|
589
600
|
throw console.error("Stream Request Failed", {
|
|
590
|
-
method:
|
|
601
|
+
method: e.method || "POST",
|
|
591
602
|
url: r,
|
|
592
|
-
status:
|
|
593
|
-
statusText:
|
|
603
|
+
status: c.status,
|
|
604
|
+
statusText: c.statusText
|
|
594
605
|
}), new Error(
|
|
595
|
-
`Stream request failed: ${
|
|
606
|
+
`Stream request failed: ${c.status} ${c.statusText}`
|
|
596
607
|
);
|
|
597
|
-
if (!
|
|
608
|
+
if (!c.body)
|
|
598
609
|
throw new Error("No response body for stream");
|
|
599
|
-
return
|
|
610
|
+
return c.body;
|
|
600
611
|
}
|
|
601
|
-
addInfoRequestLog(
|
|
602
|
-
const
|
|
603
|
-
method:
|
|
612
|
+
addInfoRequestLog(t, n, e, r) {
|
|
613
|
+
const o = {
|
|
614
|
+
method: e.method || "GET",
|
|
604
615
|
url: n,
|
|
605
|
-
headers:
|
|
616
|
+
headers: K(r)
|
|
606
617
|
};
|
|
607
|
-
|
|
618
|
+
e.body && (o.body = e.body), console.info(t, o);
|
|
608
619
|
}
|
|
609
|
-
addErrorRequestLog(
|
|
620
|
+
addErrorRequestLog(t, n, e, r, o) {
|
|
610
621
|
console.error("API Request Failed", {
|
|
611
622
|
method: n.method,
|
|
612
|
-
url:
|
|
613
|
-
status:
|
|
614
|
-
statusText:
|
|
623
|
+
url: t,
|
|
624
|
+
status: e.status,
|
|
625
|
+
statusText: e.statusText,
|
|
615
626
|
duration: `${r}ms`,
|
|
616
|
-
response:
|
|
627
|
+
response: o
|
|
617
628
|
});
|
|
618
629
|
}
|
|
619
|
-
addErrorRequestParsing(
|
|
630
|
+
addErrorRequestParsing(t, n, e, r, o) {
|
|
620
631
|
console.error("API Response Parse Error", {
|
|
621
632
|
method: n.method,
|
|
622
|
-
url:
|
|
623
|
-
status:
|
|
624
|
-
statusText:
|
|
633
|
+
url: t,
|
|
634
|
+
status: e.status,
|
|
635
|
+
statusText: e.statusText,
|
|
625
636
|
duration: `${r}ms`,
|
|
626
|
-
responseText:
|
|
637
|
+
responseText: o.substring(0, 200),
|
|
627
638
|
// First 200 chars
|
|
628
639
|
error: "Response is not valid JSON"
|
|
629
640
|
});
|
|
630
641
|
}
|
|
631
642
|
}
|
|
632
643
|
export {
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
644
|
+
$ as AttachmentType,
|
|
645
|
+
z as COMPLETION_FINISH_REASON,
|
|
646
|
+
Z as CUSTOM_VIEW_STATE_KEY,
|
|
647
|
+
G as ChatStreamSSEClient,
|
|
648
|
+
ce as ConversationApi,
|
|
638
649
|
d as DIAL_API_ROUTES,
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
650
|
+
W as DIAL_ERROR_CODES,
|
|
651
|
+
X as DIAL_ERROR_TYPES,
|
|
652
|
+
ae as DialApiClient,
|
|
642
653
|
C as ERROR_CONTEXT_KIND,
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
654
|
+
S as EXCEEDED_LIMIT,
|
|
655
|
+
Q as EXCEEDED_LIMIT_ORDER,
|
|
656
|
+
w as InvitationType,
|
|
657
|
+
N as ResourceTypes,
|
|
658
|
+
g as ShareTarget,
|
|
659
|
+
J as chatStreamSSEClient,
|
|
660
|
+
ne as decodeApiUrl,
|
|
661
|
+
h as encodeApiUrl,
|
|
662
|
+
re as formatDateTime,
|
|
663
|
+
Y as generateConversationId,
|
|
664
|
+
b as getErrorMessage,
|
|
665
|
+
B as getRateLimitRestoreDate,
|
|
666
|
+
te as getSharedConversationsRequest,
|
|
667
|
+
D as handleStreamMessage,
|
|
668
|
+
se as isRateLimitStillActive,
|
|
669
|
+
ee as mergeMessages,
|
|
670
|
+
k as parseConversationName,
|
|
671
|
+
T as sendRequest,
|
|
672
|
+
oe as streamChatResponse
|
|
662
673
|
};
|
package/models/chat-stream.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@epam/statgpt-dial-toolkit",
|
|
3
|
-
"version": "0.5.0
|
|
3
|
+
"version": "0.5.0",
|
|
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
|
|
17
|
+
"@epam/statgpt-shared-toolkit": "0.5.0",
|
|
18
18
|
"@epam/ai-dial-shared": "^0.43.3"
|
|
19
19
|
}
|
|
20
20
|
}
|