@epam/statgpt-dial-toolkit 0.7.0-dev.3 → 0.7.0-dev.31

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