@schmitech/chatbot-api 2.1.4 → 2.1.6

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/dist/api.mjs CHANGED
@@ -1,36 +1,49 @@
1
1
  var q = Object.defineProperty;
2
- var D = (l, s, e) => s in l ? q(l, s, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[s] = e;
3
- var A = (l, s, e) => D(l, typeof s != "symbol" ? s + "" : s, e);
4
- let F = null, I = null;
2
+ var D = (l, t, e) => t in l ? q(l, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[t] = e;
3
+ var g = (l, t, e) => D(l, typeof t != "symbol" ? t + "" : t, e);
4
+ let $ = null, F = null;
5
5
  typeof window > "u" && Promise.all([
6
6
  // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)
7
7
  import("http").catch(() => null),
8
8
  // @ts-expect-error - Dynamic import of Node.js built-in module (only available in Node.js runtime)
9
9
  import("https").catch(() => null)
10
- ]).then(([l, s]) => {
10
+ ]).then(([l, t]) => {
11
11
  var e, r;
12
- (e = l == null ? void 0 : l.default) != null && e.Agent ? F = new l.default.Agent({ keepAlive: !0 }) : l != null && l.Agent && (F = new l.Agent({ keepAlive: !0 })), (r = s == null ? void 0 : s.default) != null && r.Agent ? I = new s.default.Agent({ keepAlive: !0 }) : s != null && s.Agent && (I = new s.Agent({ keepAlive: !0 }));
12
+ (e = l == null ? void 0 : l.default) != null && e.Agent ? $ = new l.default.Agent({ keepAlive: !0 }) : l != null && l.Agent && ($ = new l.Agent({ keepAlive: !0 })), (r = t == null ? void 0 : t.default) != null && r.Agent ? F = new t.default.Agent({ keepAlive: !0 }) : t != null && t.Agent && (F = new t.Agent({ keepAlive: !0 }));
13
13
  }).catch((l) => {
14
14
  console.warn("Failed to initialize HTTP agents:", l.message);
15
15
  });
16
16
  class j {
17
17
  // Session ID can be mutable
18
- constructor(s) {
19
- A(this, "apiUrl");
20
- A(this, "apiKey");
21
- A(this, "sessionId");
22
- if (!s.apiUrl || typeof s.apiUrl != "string")
18
+ constructor(t) {
19
+ g(this, "apiUrl");
20
+ g(this, "apiKey");
21
+ g(this, "adapterName");
22
+ g(this, "middlewareBaseUrl");
23
+ g(this, "middlewareMode");
24
+ g(this, "sessionId");
25
+ if (!t.apiUrl || typeof t.apiUrl != "string")
23
26
  throw new Error("API URL must be a valid string");
24
- if (s.apiKey !== void 0 && s.apiKey !== null && typeof s.apiKey != "string")
27
+ if (t.apiKey !== void 0 && t.apiKey !== null && typeof t.apiKey != "string")
25
28
  throw new Error("API key must be a valid string or null");
26
- if (s.sessionId !== void 0 && s.sessionId !== null && typeof s.sessionId != "string")
29
+ if (t.sessionId !== void 0 && t.sessionId !== null && typeof t.sessionId != "string")
27
30
  throw new Error("Session ID must be a valid string or null");
28
- this.apiUrl = s.apiUrl, this.apiKey = s.apiKey ?? null, this.sessionId = s.sessionId ?? null;
31
+ if (t.adapterName !== void 0 && t.adapterName !== null && typeof t.adapterName != "string")
32
+ throw new Error("Adapter name must be a valid string or null");
33
+ if (t.middlewareBaseUrl !== void 0 && t.middlewareBaseUrl !== null && typeof t.middlewareBaseUrl != "string")
34
+ throw new Error("Middleware base URL must be a valid string or null");
35
+ this.apiUrl = t.apiUrl, this.apiKey = t.apiKey ?? null, this.sessionId = t.sessionId ?? null;
36
+ const e = typeof t.adapterName == "string" ? t.adapterName.trim() : "";
37
+ this.adapterName = e && e.length > 0 ? e : null;
38
+ const r = typeof t.middlewareBaseUrl == "string" ? t.middlewareBaseUrl.trim() : "";
39
+ this.middlewareBaseUrl = r.endsWith("/") ? r.slice(0, -1) : r;
40
+ const s = t.useMiddleware ?? (!this.apiKey && !!this.adapterName);
41
+ this.middlewareMode = !!(this.adapterName && s);
29
42
  }
30
- setSessionId(s) {
31
- if (s !== null && typeof s != "string")
43
+ setSessionId(t) {
44
+ if (t !== null && typeof t != "string")
32
45
  throw new Error("Session ID must be a valid string or null");
33
- this.sessionId = s;
46
+ this.sessionId = t;
34
47
  }
35
48
  getSessionId() {
36
49
  return this.sessionId;
@@ -42,7 +55,7 @@ class j {
42
55
  * @throws Error if API key is not provided, invalid, inactive, or validation fails
43
56
  */
44
57
  async validateApiKey() {
45
- var s;
58
+ var t;
46
59
  if (!this.apiKey)
47
60
  throw new Error("API key is required for validation");
48
61
  try {
@@ -50,22 +63,22 @@ class j {
50
63
  ...this.getFetchOptions({
51
64
  method: "GET"
52
65
  })
53
- }).catch((t) => {
54
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
66
+ }).catch((s) => {
67
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
55
68
  });
56
69
  if (!e.ok) {
57
- let t = "";
70
+ let s = "";
58
71
  try {
59
- t = await e.text();
72
+ s = await e.text();
60
73
  } catch {
61
- t = `HTTP ${e.status}`;
74
+ s = `HTTP ${e.status}`;
62
75
  }
63
76
  let i, n;
64
77
  try {
65
- const o = JSON.parse(t);
66
- i = o.detail || o.message || t;
78
+ const o = JSON.parse(s);
79
+ i = o.detail || o.message || s;
67
80
  } catch {
68
- i = t || `HTTP ${e.status}`;
81
+ i = s || `HTTP ${e.status}`;
69
82
  }
70
83
  switch (e.status) {
71
84
  case 401:
@@ -88,17 +101,17 @@ class j {
88
101
  }
89
102
  const r = await e.json();
90
103
  if (!r.exists) {
91
- const t = "API key does not exist";
92
- throw new Error(t);
104
+ const s = "API key does not exist";
105
+ throw new Error(s);
93
106
  }
94
107
  if (!r.active) {
95
- const t = "API key is inactive";
96
- throw new Error(t);
108
+ const s = "API key is inactive";
109
+ throw new Error(s);
97
110
  }
98
111
  return r;
99
112
  } catch (e) {
100
113
  let r;
101
- throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Access denied") || e.message.includes("invalid") || e.message.includes("expired") || e.message.includes("inactive") || e.message.includes("not found") || e.message.includes("Could not connect") ? r = e.message : r = `API key validation failed: ${e.message}` : e.name === "TypeError" && ((s = e.message) != null && s.includes("Failed to fetch")) ? r = "Could not connect to the server. Please check if the server is running." : r = "API key validation failed. Please check your API key and try again.", console.warn(`[ApiClient] ${r}`), new Error(r);
114
+ throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Access denied") || e.message.includes("invalid") || e.message.includes("expired") || e.message.includes("inactive") || e.message.includes("not found") || e.message.includes("Could not connect") ? r = e.message : r = `API key validation failed: ${e.message}` : e.name === "TypeError" && ((t = e.message) != null && t.includes("Failed to fetch")) ? r = "Could not connect to the server. Please check if the server is running." : r = "API key validation failed. Please check your API key and try again.", console.warn(`[ApiClient] ${r}`), new Error(r);
102
115
  }
103
116
  }
104
117
  /**
@@ -111,7 +124,7 @@ class j {
111
124
  * @throws Error if API key is not provided, invalid, disabled, or request fails
112
125
  */
113
126
  async getAdapterInfo() {
114
- var s;
127
+ var t;
115
128
  if (!this.apiKey)
116
129
  throw new Error("API key is required to get adapter information");
117
130
  try {
@@ -119,22 +132,22 @@ class j {
119
132
  ...this.getFetchOptions({
120
133
  method: "GET"
121
134
  })
122
- }).catch((t) => {
123
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
135
+ }).catch((s) => {
136
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
124
137
  });
125
138
  if (!e.ok) {
126
- let t = "";
139
+ let s = "";
127
140
  try {
128
- t = await e.text();
141
+ s = await e.text();
129
142
  } catch {
130
- t = `HTTP ${e.status}`;
143
+ s = `HTTP ${e.status}`;
131
144
  }
132
145
  let i, n;
133
146
  try {
134
- const o = JSON.parse(t);
135
- i = o.detail || o.message || t;
147
+ const o = JSON.parse(s);
148
+ i = o.detail || o.message || s;
136
149
  } catch {
137
- i = t || `HTTP ${e.status}`;
150
+ i = s || `HTTP ${e.status}`;
138
151
  }
139
152
  switch (e.status) {
140
153
  case 401:
@@ -155,45 +168,93 @@ class j {
155
168
  return await e.json();
156
169
  } catch (e) {
157
170
  let r;
158
- throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Adapter") || e.message.includes("invalid") || e.message.includes("disabled") || e.message.includes("not found") || e.message.includes("Could not connect") ? r = e.message : r = `Failed to get adapter info: ${e.message}` : e.name === "TypeError" && ((s = e.message) != null && s.includes("Failed to fetch")) ? r = "Could not connect to the server. Please check if the server is running." : r = "Failed to get adapter information. Please try again.", console.warn(`[ApiClient] ${r}`), new Error(r);
171
+ throw e instanceof Error && e.message ? e.message.includes("API key") || e.message.includes("Adapter") || e.message.includes("invalid") || e.message.includes("disabled") || e.message.includes("not found") || e.message.includes("Could not connect") ? r = e.message : r = `Failed to get adapter info: ${e.message}` : e.name === "TypeError" && ((t = e.message) != null && t.includes("Failed to fetch")) ? r = "Could not connect to the server. Please check if the server is running." : r = "Failed to get adapter information. Please try again.", console.warn(`[ApiClient] ${r}`), new Error(r);
172
+ }
173
+ }
174
+ /**
175
+ * Get autocomplete suggestions based on query prefix.
176
+ *
177
+ * Returns query suggestions based on nl_examples from intent adapter templates.
178
+ * This is useful for helping users discover available queries.
179
+ *
180
+ * @param query - The query prefix (minimum 3 characters)
181
+ * @param limit - Maximum number of suggestions (default: 5)
182
+ * @returns Promise resolving to autocomplete suggestions
183
+ */
184
+ async getAutocompleteSuggestions(t, e = 5) {
185
+ if (t.length < 3)
186
+ return { suggestions: [], query: t };
187
+ const r = this.middlewareMode && !!this.adapterName;
188
+ if (!r && !this.apiKey)
189
+ return { suggestions: [], query: t };
190
+ try {
191
+ const s = new URLSearchParams();
192
+ s.set("q", t), s.set("limit", String(e));
193
+ let i, n;
194
+ if (r) {
195
+ if (!this.middlewareBaseUrl && typeof window > "u")
196
+ throw new Error("middlewareBaseUrl must be set when using middleware outside the browser environment.");
197
+ i = `${this.middlewareBaseUrl ? this.middlewareBaseUrl : ""}/api/v1/autocomplete?${s.toString()}`;
198
+ const f = {
199
+ "X-Adapter-Name": this.adapterName,
200
+ "X-Request-ID": Date.now().toString(36) + Math.random().toString(36).substring(2)
201
+ };
202
+ this.sessionId && (f["X-Session-ID"] = this.sessionId), n = {
203
+ method: "GET",
204
+ headers: f
205
+ };
206
+ } else {
207
+ const d = new URL(`${this.apiUrl}/v1/autocomplete`);
208
+ d.searchParams.set("q", t), d.searchParams.set("limit", String(e)), i = d.toString(), n = {
209
+ ...this.getFetchOptions({
210
+ method: "GET"
211
+ })
212
+ };
213
+ }
214
+ const o = await fetch(i, n);
215
+ return o.ok ? await o.json() : (console.warn("[ApiClient] Autocomplete request failed:", o.status), { suggestions: [], query: t });
216
+ } catch (s) {
217
+ return console.warn("[ApiClient] Autocomplete error:", s.message), { suggestions: [], query: t };
159
218
  }
160
219
  }
161
220
  // Helper to get fetch options with connection pooling if available
162
- getFetchOptions(s = {}) {
221
+ getFetchOptions(t = {}) {
163
222
  const e = {};
164
223
  if (typeof window > "u") {
165
- const i = this.apiUrl.startsWith("https:") ? I : F;
224
+ const i = this.apiUrl.startsWith("https:") ? F : $;
166
225
  i && (e.agent = i);
167
226
  } else
168
227
  e.headers = { Connection: "keep-alive" };
169
228
  const r = {
170
229
  "X-Request-ID": Date.now().toString(36) + Math.random().toString(36).substring(2)
171
230
  };
172
- if (e.headers && Object.assign(r, e.headers), s.headers) {
173
- const t = s.headers;
174
- for (const [i, n] of Object.entries(t))
231
+ if (e.headers && Object.assign(r, e.headers), t.headers) {
232
+ const s = t.headers;
233
+ for (const [i, n] of Object.entries(s))
175
234
  (i.toLowerCase() !== "x-api-key" || !this.apiKey) && (r[i] = n);
176
235
  }
177
236
  return this.apiKey && (r["X-API-Key"] = this.apiKey), this.sessionId && (r["X-Session-ID"] = this.sessionId), {
178
- ...s,
237
+ ...t,
179
238
  ...e,
180
239
  headers: r
181
240
  };
182
241
  }
183
242
  // Create Chat request
184
- createChatRequest(s, e = !0, r, t, i, n, o, c, u, f, v) {
185
- const d = {
243
+ createChatRequest(t, e = !0, r, s, i, n, o, d, u, f, m) {
244
+ const c = {
186
245
  messages: [
187
- { role: "user", content: s }
246
+ { role: "user", content: t }
188
247
  ],
189
248
  stream: e
190
249
  };
191
- return r && r.length > 0 && (d.file_ids = r), t && (d.thread_id = t), i && (d.audio_input = i), n && (d.audio_format = n), o && (d.language = o), c !== void 0 && (d.return_audio = c), u && (d.tts_voice = u), f && (d.source_language = f), v && (d.target_language = v), d;
250
+ return r && r.length > 0 && (c.file_ids = r), s && (c.thread_id = s), i && (c.audio_input = i), n && (c.audio_format = n), o && (c.language = o), d !== void 0 && (c.return_audio = d), u && (c.tts_voice = u), f && (c.source_language = f), m && (c.target_language = m), c;
192
251
  }
193
- async *streamChat(s, e = !0, r, t, i, n, o, c, u, f, v) {
194
- var d, C, x;
252
+ async *streamChat(t, e = !0, r, s, i, n, o, d, u, f, m, c) {
253
+ var C, b, x;
195
254
  try {
196
- const p = new AbortController(), O = setTimeout(() => p.abort(), 6e4), g = await fetch(`${this.apiUrl}/v1/chat`, {
255
+ const w = new AbortController(), K = setTimeout(() => w.abort(), 6e4);
256
+ c && c.addEventListener("abort", () => w.abort());
257
+ const v = await fetch(`${this.apiUrl}/v1/chat`, {
197
258
  ...this.getFetchOptions({
198
259
  method: "POST",
199
260
  headers: {
@@ -201,27 +262,27 @@ class j {
201
262
  Accept: e ? "text/event-stream" : "application/json"
202
263
  },
203
264
  body: JSON.stringify(this.createChatRequest(
204
- s,
265
+ t,
205
266
  e,
206
267
  r,
207
- t,
268
+ s,
208
269
  i,
209
270
  n,
210
271
  o,
211
- c,
272
+ d,
212
273
  u,
213
274
  f,
214
- v
275
+ m
215
276
  ))
216
277
  }),
217
- signal: p.signal
278
+ signal: w.signal
218
279
  });
219
- if (clearTimeout(O), !g.ok) {
220
- const y = await g.text();
221
- throw new Error(`Network response was not ok: ${g.status} ${y}`);
280
+ if (clearTimeout(K), !v.ok) {
281
+ const y = await v.text();
282
+ throw new Error(`Network response was not ok: ${v.status} ${y}`);
222
283
  }
223
284
  if (!e) {
224
- const y = await g.json();
285
+ const y = await v.json();
225
286
  y.response && (yield {
226
287
  text: y.response,
227
288
  done: !0,
@@ -230,23 +291,23 @@ class j {
230
291
  });
231
292
  return;
232
293
  }
233
- const P = (d = g.body) == null ? void 0 : d.getReader();
234
- if (!P) throw new Error("No reader available");
294
+ const I = (C = v.body) == null ? void 0 : C.getReader();
295
+ if (!I) throw new Error("No reader available");
235
296
  const S = new TextDecoder();
236
- let w = "", k = !1;
297
+ let p = "", A = !1;
237
298
  try {
238
299
  for (; ; ) {
239
- const { done: y, value: U } = await P.read();
300
+ const { done: y, value: N } = await I.read();
240
301
  if (y)
241
302
  break;
242
- const _ = S.decode(U, { stream: !0 });
243
- w += _;
244
- let E = 0, T;
245
- for (; (T = w.indexOf(`
246
- `, E)) !== -1; ) {
247
- const m = w.slice(E, T).trim();
248
- if (E = T + 1, m && m.startsWith("data: ")) {
249
- const h = m.slice(6).trim();
303
+ const _ = S.decode(N, { stream: !0 });
304
+ p += _;
305
+ let P = 0, T;
306
+ for (; (T = p.indexOf(`
307
+ `, P)) !== -1; ) {
308
+ const E = p.slice(P, T).trim();
309
+ if (P = T + 1, E && E.startsWith("data: ")) {
310
+ const h = E.slice(6).trim();
250
311
  if (!h || h === "[DONE]") {
251
312
  yield { text: "", done: !0 };
252
313
  return;
@@ -254,11 +315,19 @@ class j {
254
315
  try {
255
316
  const a = JSON.parse(h);
256
317
  if (a.error) {
257
- const K = `Server error: ${((C = a.error) == null ? void 0 : C.message) || a.error || "Unknown server error"}`;
258
- throw console.warn(`[ApiClient] ${K}`), new Error(K);
318
+ const O = `Server error: ${((b = a.error) == null ? void 0 : b.message) || a.error || "Unknown server error"}`;
319
+ throw console.warn(`[ApiClient] ${O}`), new Error(O);
320
+ }
321
+ if (a.request_id && !a.response && !a.done) {
322
+ yield {
323
+ text: "",
324
+ done: !1,
325
+ request_id: a.request_id
326
+ };
327
+ continue;
259
328
  }
260
329
  if (a.done === !0) {
261
- k = !0, yield {
330
+ A = !0, yield {
262
331
  text: "",
263
332
  done: !0,
264
333
  audio: a.audio,
@@ -268,15 +337,15 @@ class j {
268
337
  };
269
338
  return;
270
339
  }
271
- const b = a.response || "";
340
+ const U = a.response || "";
272
341
  a.audio_chunk !== void 0 && (yield {
273
342
  text: "",
274
343
  done: !1,
275
344
  audio_chunk: a.audio_chunk,
276
345
  audioFormat: a.audioFormat || a.audio_format || "opus",
277
346
  chunk_index: a.chunk_index ?? 0
278
- }), (b || a.audio) && (k = !0, yield {
279
- text: b,
347
+ }), (U || a.audio) && (A = !0, yield {
348
+ text: U,
280
349
  done: a.done || !1,
281
350
  audio: a.audio,
282
351
  audioFormat: a.audio_format || a.audioFormat,
@@ -288,49 +357,75 @@ class j {
288
357
  throw a;
289
358
  console.warn("[ApiClient] Unable to parse server response. This may be a temporary issue."), console.warn("[ApiClient] Parse error details:", a == null ? void 0 : a.message), console.warn("[ApiClient] JSON text length:", h == null ? void 0 : h.length), console.warn("[ApiClient] JSON text preview (first 200 chars):", h == null ? void 0 : h.substring(0, 200)), console.warn("[ApiClient] JSON text preview (last 200 chars):", h == null ? void 0 : h.substring(h.length - 200));
290
359
  }
291
- } else m && (k = !0, yield { text: m, done: !1 });
360
+ } else E && (A = !0, yield { text: E, done: !1 });
292
361
  }
293
- w = w.slice(E), w.length > 1e6 && (console.warn("[ApiClient] Buffer too large, truncating..."), w = w.slice(-5e5));
362
+ p = p.slice(P), p.length > 1e6 && (console.warn("[ApiClient] Buffer too large, truncating..."), p = p.slice(-5e5));
294
363
  }
295
- k && (yield { text: "", done: !0 });
364
+ A && (yield { text: "", done: !0 });
296
365
  } finally {
297
- P.releaseLock();
366
+ I.releaseLock();
298
367
  }
299
- } catch (p) {
300
- throw p.name === "AbortError" ? new Error("Connection timed out. Please check if the server is running.") : p.name === "TypeError" && p.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : p;
368
+ } catch (w) {
369
+ throw w.name === "AbortError" ? c != null && c.aborted ? new Error("Stream cancelled by user") : new Error("Connection timed out. Please check if the server is running.") : w.name === "TypeError" && w.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : w;
301
370
  }
302
371
  }
303
- async getConversationHistory(s, e) {
304
- const r = s || this.sessionId;
372
+ /**
373
+ * Stop an active streaming request.
374
+ *
375
+ * @param sessionId - The session identifier
376
+ * @param requestId - The request identifier (from first stream chunk)
377
+ * @returns Promise resolving to true if stream was cancelled, false otherwise
378
+ */
379
+ async stopChat(t, e) {
380
+ try {
381
+ const r = await fetch(`${this.apiUrl}/v1/chat/stop`, {
382
+ ...this.getFetchOptions({
383
+ method: "POST",
384
+ headers: {
385
+ "Content-Type": "application/json"
386
+ },
387
+ body: JSON.stringify({
388
+ session_id: t,
389
+ request_id: e
390
+ })
391
+ })
392
+ });
393
+ return r.ok ? (await r.json()).status === "cancelled" : (console.warn("[ApiClient] Failed to stop stream:", r.status), !1);
394
+ } catch (r) {
395
+ return console.error("[ApiClient] Error stopping stream:", r), !1;
396
+ }
397
+ }
398
+ async getConversationHistory(t, e) {
399
+ const r = t || this.sessionId;
305
400
  if (!r)
306
401
  throw new Error("No session ID provided and no current session available");
307
- const t = {};
308
- this.apiKey && (t["X-API-Key"] = this.apiKey);
402
+ const s = {};
403
+ this.apiKey && (s["X-API-Key"] = this.apiKey);
309
404
  try {
310
405
  const i = new URL(`${this.apiUrl}/admin/chat-history/${r}`);
311
406
  typeof e == "number" && Number.isFinite(e) && e > 0 && i.searchParams.set("limit", String(Math.floor(e)));
312
407
  const n = await fetch(i.toString(), {
313
408
  ...this.getFetchOptions({
314
409
  method: "GET",
315
- headers: t
410
+ headers: s
316
411
  })
317
412
  });
318
413
  if (!n.ok) {
319
414
  const f = await n.text();
320
415
  throw new Error(`Failed to fetch conversation history: ${n.status} ${f}`);
321
416
  }
322
- const o = await n.json(), c = Array.isArray(o == null ? void 0 : o.messages) ? o.messages : [], u = typeof (o == null ? void 0 : o.count) == "number" ? o.count : c.length;
417
+ const o = await n.json(), d = Array.isArray(o == null ? void 0 : o.messages) ? o.messages : [], u = typeof (o == null ? void 0 : o.count) == "number" ? o.count : d.length;
323
418
  return {
324
419
  session_id: (o == null ? void 0 : o.session_id) || r,
325
- messages: c,
420
+ messages: d,
326
421
  count: u
327
422
  };
328
423
  } catch (i) {
329
424
  throw i.name === "TypeError" && i.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : i;
330
425
  }
331
426
  }
332
- async clearConversationHistory(s) {
333
- const e = s || this.sessionId;
427
+ async clearConversationHistory(t) {
428
+ const e = t || this.sessionId;
334
429
  if (!e)
335
430
  throw new Error("No session ID provided and no current session available");
336
431
  if (!this.apiKey)
@@ -341,28 +436,28 @@ class j {
341
436
  "X-API-Key": this.apiKey
342
437
  };
343
438
  try {
344
- const t = await fetch(`${this.apiUrl}/admin/chat-history/${e}`, {
439
+ const s = await fetch(`${this.apiUrl}/admin/chat-history/${e}`, {
345
440
  ...this.getFetchOptions({
346
441
  method: "DELETE",
347
442
  headers: r
348
443
  })
349
444
  });
350
- if (!t.ok) {
351
- const n = await t.text();
352
- throw new Error(`Failed to clear conversation history: ${t.status} ${n}`);
445
+ if (!s.ok) {
446
+ const n = await s.text();
447
+ throw new Error(`Failed to clear conversation history: ${s.status} ${n}`);
353
448
  }
354
- return await t.json();
355
- } catch (t) {
356
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
449
+ return await s.json();
450
+ } catch (s) {
451
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
357
452
  }
358
453
  }
359
- async deleteConversationWithFiles(s, e) {
360
- const r = s || this.sessionId;
454
+ async deleteConversationWithFiles(t, e) {
455
+ const r = t || this.sessionId;
361
456
  if (!r)
362
457
  throw new Error("No session ID provided and no current session available");
363
458
  if (!this.apiKey)
364
459
  throw new Error("API key is required for deleting conversation");
365
- const t = {
460
+ const s = {
366
461
  "Content-Type": "application/json",
367
462
  "X-Session-ID": r,
368
463
  "X-API-Key": this.apiKey
@@ -371,7 +466,7 @@ class j {
371
466
  const o = await fetch(n, {
372
467
  ...this.getFetchOptions({
373
468
  method: "DELETE",
374
- headers: t
469
+ headers: s
375
470
  })
376
471
  });
377
472
  if (!o.ok) {
@@ -391,7 +486,7 @@ class j {
391
486
  * @returns Promise resolving to thread information
392
487
  * @throws Error if the operation fails
393
488
  */
394
- async createThread(s, e) {
489
+ async createThread(t, e) {
395
490
  if (!this.apiKey)
396
491
  throw new Error("API key is required for creating threads");
397
492
  const r = {
@@ -399,23 +494,23 @@ class j {
399
494
  "X-API-Key": this.apiKey
400
495
  };
401
496
  try {
402
- const t = await fetch(`${this.apiUrl}/api/threads`, {
497
+ const s = await fetch(`${this.apiUrl}/api/threads`, {
403
498
  ...this.getFetchOptions({
404
499
  method: "POST",
405
500
  headers: r,
406
501
  body: JSON.stringify({
407
- message_id: s,
502
+ message_id: t,
408
503
  session_id: e
409
504
  })
410
505
  })
411
506
  });
412
- if (!t.ok) {
413
- const n = await t.text();
414
- throw new Error(`Failed to create thread: ${t.status} ${n}`);
507
+ if (!s.ok) {
508
+ const n = await s.text();
509
+ throw new Error(`Failed to create thread: ${s.status} ${n}`);
415
510
  }
416
- return await t.json();
417
- } catch (t) {
418
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
511
+ return await s.json();
512
+ } catch (s) {
513
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
419
514
  }
420
515
  }
421
516
  /**
@@ -425,14 +520,14 @@ class j {
425
520
  * @returns Promise resolving to thread information
426
521
  * @throws Error if the operation fails
427
522
  */
428
- async getThreadInfo(s) {
523
+ async getThreadInfo(t) {
429
524
  if (!this.apiKey)
430
525
  throw new Error("API key is required for getting thread info");
431
526
  const e = {
432
527
  "X-API-Key": this.apiKey
433
528
  };
434
529
  try {
435
- const r = await fetch(`${this.apiUrl}/api/threads/${s}`, {
530
+ const r = await fetch(`${this.apiUrl}/api/threads/${t}`, {
436
531
  ...this.getFetchOptions({
437
532
  method: "GET",
438
533
  headers: e
@@ -454,14 +549,14 @@ class j {
454
549
  * @returns Promise resolving to deletion result
455
550
  * @throws Error if the operation fails
456
551
  */
457
- async deleteThread(s) {
552
+ async deleteThread(t) {
458
553
  if (!this.apiKey)
459
554
  throw new Error("API key is required for deleting threads");
460
555
  const e = {
461
556
  "X-API-Key": this.apiKey
462
557
  };
463
558
  try {
464
- const r = await fetch(`${this.apiUrl}/api/threads/${s}`, {
559
+ const r = await fetch(`${this.apiUrl}/api/threads/${t}`, {
465
560
  ...this.getFetchOptions({
466
561
  method: "DELETE",
467
562
  headers: e
@@ -483,11 +578,11 @@ class j {
483
578
  * @returns Promise resolving to upload response with file_id
484
579
  * @throws Error if upload fails
485
580
  */
486
- async uploadFile(s) {
581
+ async uploadFile(t) {
487
582
  if (!this.apiKey)
488
583
  throw new Error("API key is required for file upload");
489
584
  const e = new FormData();
490
- e.append("file", s);
585
+ e.append("file", t);
491
586
  try {
492
587
  const r = await fetch(`${this.apiUrl}/api/files/upload`, {
493
588
  ...this.getFetchOptions({
@@ -496,8 +591,8 @@ class j {
496
591
  })
497
592
  });
498
593
  if (!r.ok) {
499
- const t = await r.text();
500
- throw new Error(`Failed to upload file: ${r.status} ${t}`);
594
+ const s = await r.text();
595
+ throw new Error(`Failed to upload file: ${r.status} ${s}`);
501
596
  }
502
597
  return await r.json();
503
598
  } catch (r) {
@@ -514,18 +609,18 @@ class j {
514
609
  if (!this.apiKey)
515
610
  throw new Error("API key is required for listing files");
516
611
  try {
517
- const s = await fetch(`${this.apiUrl}/api/files`, {
612
+ const t = await fetch(`${this.apiUrl}/api/files`, {
518
613
  ...this.getFetchOptions({
519
614
  method: "GET"
520
615
  })
521
616
  });
522
- if (!s.ok) {
523
- const e = await s.text();
524
- throw new Error(`Failed to list files: ${s.status} ${e}`);
617
+ if (!t.ok) {
618
+ const e = await t.text();
619
+ throw new Error(`Failed to list files: ${t.status} ${e}`);
525
620
  }
526
- return await s.json();
527
- } catch (s) {
528
- throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
621
+ return await t.json();
622
+ } catch (t) {
623
+ throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
529
624
  }
530
625
  }
531
626
  /**
@@ -535,11 +630,11 @@ class j {
535
630
  * @returns Promise resolving to file information
536
631
  * @throws Error if file not found or request fails
537
632
  */
538
- async getFileInfo(s) {
633
+ async getFileInfo(t) {
539
634
  if (!this.apiKey)
540
635
  throw new Error("API key is required for getting file info");
541
636
  try {
542
- const e = await fetch(`${this.apiUrl}/api/files/${s}`, {
637
+ const e = await fetch(`${this.apiUrl}/api/files/${t}`, {
543
638
  ...this.getFetchOptions({
544
639
  method: "GET"
545
640
  })
@@ -562,11 +657,11 @@ class j {
562
657
  * @returns Promise resolving to query results
563
658
  * @throws Error if query fails
564
659
  */
565
- async queryFile(s, e, r = 10) {
660
+ async queryFile(t, e, r = 10) {
566
661
  if (!this.apiKey)
567
662
  throw new Error("API key is required for querying files");
568
663
  try {
569
- const t = await fetch(`${this.apiUrl}/api/files/${s}/query`, {
664
+ const s = await fetch(`${this.apiUrl}/api/files/${t}/query`, {
570
665
  ...this.getFetchOptions({
571
666
  method: "POST",
572
667
  headers: {
@@ -575,13 +670,13 @@ class j {
575
670
  body: JSON.stringify({ query: e, max_results: r })
576
671
  })
577
672
  });
578
- if (!t.ok) {
579
- const i = await t.text();
580
- throw new Error(`Failed to query file: ${t.status} ${i}`);
673
+ if (!s.ok) {
674
+ const i = await s.text();
675
+ throw new Error(`Failed to query file: ${s.status} ${i}`);
581
676
  }
582
- return await t.json();
583
- } catch (t) {
584
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : t;
677
+ return await s.json();
678
+ } catch (s) {
679
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? new Error("Could not connect to the server. Please check if the server is running.") : s;
585
680
  }
586
681
  }
587
682
  /**
@@ -591,56 +686,63 @@ class j {
591
686
  * @returns Promise resolving to deletion result
592
687
  * @throws Error if deletion fails
593
688
  */
594
- async deleteFile(s) {
689
+ async deleteFile(t) {
595
690
  if (!this.apiKey)
596
691
  throw new Error("API key is required for deleting files");
597
- const e = `${this.apiUrl}/api/files/${s}`, r = this.getFetchOptions({
692
+ const e = `${this.apiUrl}/api/files/${t}`, r = this.getFetchOptions({
598
693
  method: "DELETE"
599
694
  });
600
695
  try {
601
- const t = await fetch(e, r);
602
- if (!t.ok) {
603
- const n = await t.text();
696
+ const s = await fetch(e, r);
697
+ if (!s.ok) {
698
+ const n = await s.text();
604
699
  let o;
605
700
  try {
606
- const c = JSON.parse(n);
607
- o = c.detail || c.message || `Failed to delete file (HTTP ${t.status})`;
701
+ const d = JSON.parse(n);
702
+ o = d.detail || d.message || `Failed to delete file (HTTP ${s.status})`;
608
703
  } catch {
609
- o = `Failed to delete file (HTTP ${t.status})`;
704
+ o = `Failed to delete file (HTTP ${s.status})`;
610
705
  }
611
706
  throw console.warn(`[ApiClient] ${o}`), new Error(o);
612
707
  }
613
- return await t.json();
614
- } catch (t) {
708
+ return await s.json();
709
+ } catch (s) {
615
710
  let i;
616
- throw t.name === "TypeError" && t.message.includes("Failed to fetch") ? i = "Could not connect to the server. Please check if the server is running." : t.message && !t.message.includes("Failed to delete file") ? i = t.message : i = "Failed to delete file. Please try again.", console.warn(`[ApiClient] ${i}`), new Error(i);
711
+ throw s.name === "TypeError" && s.message.includes("Failed to fetch") ? i = "Could not connect to the server. Please check if the server is running." : s.message && !s.message.includes("Failed to delete file") ? i = s.message : i = "Failed to delete file. Please try again.", console.warn(`[ApiClient] ${i}`), new Error(i);
617
712
  }
618
713
  }
619
714
  }
620
- let $ = null;
621
- const M = (l, s = null, e = null) => {
622
- $ = new j({ apiUrl: l, apiKey: s, sessionId: e });
715
+ let k = null;
716
+ const R = (l, t = null, e = null) => {
717
+ k = new j({ apiUrl: l, apiKey: t, sessionId: e });
623
718
  };
624
- async function* H(l, s = !0, e, r, t, i, n, o, c, u, f) {
625
- if (!$)
719
+ async function* X(l, t = !0, e, r, s, i, n, o, d, u, f, m) {
720
+ if (!k)
626
721
  throw new Error("API not configured. Please call configureApi() with your server URL before using any API functions.");
627
- yield* $.streamChat(
722
+ yield* k.streamChat(
628
723
  l,
629
- s,
724
+ t,
630
725
  e,
631
726
  r,
632
- t,
727
+ s,
633
728
  i,
634
729
  n,
635
730
  o,
636
- c,
731
+ d,
637
732
  u,
638
- f
733
+ f,
734
+ m
639
735
  );
640
736
  }
737
+ async function B(l, t) {
738
+ if (!k)
739
+ throw new Error("API not configured. Please call configureApi() with your server URL before using any API functions.");
740
+ return k.stopChat(l, t);
741
+ }
641
742
  export {
642
743
  j as ApiClient,
643
- M as configureApi,
644
- H as streamChat
744
+ R as configureApi,
745
+ B as stopChat,
746
+ X as streamChat
645
747
  };
646
748
  //# sourceMappingURL=api.mjs.map