@terryavg/neptune-ai-chatbot 1.0.1 → 1.0.3

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 (74) hide show
  1. package/README.md +116 -1
  2. package/dist/chat-input-2CHIBULE.mjs +510 -0
  3. package/dist/chat-input-42V4ESQB.mjs +478 -0
  4. package/dist/chat-input-4T42R7FR.mjs +481 -0
  5. package/dist/chat-input-BJVIIYOP.mjs +484 -0
  6. package/dist/chat-input-G2LRENLB.mjs +512 -0
  7. package/dist/chat-input-HT47ZLQN.mjs +456 -0
  8. package/dist/chat-input-IIV2HQOZ.mjs +509 -0
  9. package/dist/chat-input-JFGPZBBQ.mjs +495 -0
  10. package/dist/chat-input-JQ7PSHNW.mjs +515 -0
  11. package/dist/chat-input-MLF62KV7.mjs +512 -0
  12. package/dist/chat-input-MOPCNDRR.mjs +517 -0
  13. package/dist/chat-input-TYNO3J5S.mjs +519 -0
  14. package/dist/chat-input-USWVSAYY.mjs +461 -0
  15. package/dist/chat-input-VQZ3WNBT.mjs +509 -0
  16. package/dist/chat-input-VTCTV5ED.mjs +495 -0
  17. package/dist/chat-input-WJMGLQJI.mjs +495 -0
  18. package/dist/chat-input-ZAFYBUO7.mjs +507 -0
  19. package/dist/chat-message-2VQW74CO.mjs +2230 -0
  20. package/dist/chat-message-35ZWSSQV.mjs +1926 -0
  21. package/dist/chat-message-3CUUWTZG.mjs +2429 -0
  22. package/dist/chat-message-3NHSJNKL.mjs +2241 -0
  23. package/dist/chat-message-3Z7B2WYC.mjs +2228 -0
  24. package/dist/chat-message-564AHZHH.mjs +2186 -0
  25. package/dist/chat-message-5QLTW4K7.mjs +2122 -0
  26. package/dist/chat-message-7EH2TDZG.mjs +1910 -0
  27. package/dist/chat-message-7QHJRHQG.mjs +1909 -0
  28. package/dist/chat-message-AAXNH5TF.mjs +2088 -0
  29. package/dist/chat-message-D36YF274.mjs +1910 -0
  30. package/dist/chat-message-DVCXEL4Z.mjs +2111 -0
  31. package/dist/chat-message-E6KB3AST.mjs +1906 -0
  32. package/dist/chat-message-EQTB6N5X.mjs +2306 -0
  33. package/dist/chat-message-G2NWPAXK.mjs +1904 -0
  34. package/dist/chat-message-GUOL4RZU.mjs +2306 -0
  35. package/dist/chat-message-H62Z3DW5.mjs +2368 -0
  36. package/dist/chat-message-HIEZ7B5R.mjs +2190 -0
  37. package/dist/chat-message-HWBFOYOJ.mjs +2306 -0
  38. package/dist/chat-message-I6AKFPK6.mjs +2156 -0
  39. package/dist/chat-message-IKYSAVAB.mjs +1918 -0
  40. package/dist/chat-message-IZL6JHV2.mjs +2429 -0
  41. package/dist/chat-message-J7PVUQO6.mjs +1878 -0
  42. package/dist/chat-message-K6QILTW5.mjs +1897 -0
  43. package/dist/chat-message-MDORLI2R.mjs +2228 -0
  44. package/dist/chat-message-MFUY6KOE.mjs +1910 -0
  45. package/dist/chat-message-MYKOR5OF.mjs +1890 -0
  46. package/dist/chat-message-NKMTAMGG.mjs +1906 -0
  47. package/dist/chat-message-NNGD3FUH.mjs +2168 -0
  48. package/dist/chat-message-NZNZX6VS.mjs +2306 -0
  49. package/dist/chat-message-QAPRO542.mjs +1915 -0
  50. package/dist/chat-message-R4IJ3MXU.mjs +2146 -0
  51. package/dist/chat-message-U7UCBLHI.mjs +2145 -0
  52. package/dist/chat-message-UKXGFKUR.mjs +1903 -0
  53. package/dist/chat-message-UNIBCF3T.mjs +1900 -0
  54. package/dist/chat-message-UXLPL76T.mjs +1890 -0
  55. package/dist/chat-message-VB54UOHB.mjs +2306 -0
  56. package/dist/chat-message-WUNUZLKI.mjs +2228 -0
  57. package/dist/chat-message-WYN5UZRD.mjs +1927 -0
  58. package/dist/chat-message-Y5OJSR2O.mjs +2228 -0
  59. package/dist/chat-message-YPDHL6WW.mjs +2114 -0
  60. package/dist/chunk-26656QB3.mjs +406 -0
  61. package/dist/chunk-2RXQ2EZ2.mjs +295 -0
  62. package/dist/chunk-DVWFDUN4.mjs +407 -0
  63. package/dist/chunk-JLRHY3SB.mjs +405 -0
  64. package/dist/chunk-VONUV37R.mjs +268 -0
  65. package/dist/chunk-XFSEOBLD.mjs +432 -0
  66. package/dist/chunk-XQVUOR36.mjs +438 -0
  67. package/dist/chunk-Y7QF5535.mjs +268 -0
  68. package/dist/index.css +174 -43
  69. package/dist/index.d.mts +214 -2
  70. package/dist/index.d.ts +214 -2
  71. package/dist/index.js +2232 -1839
  72. package/dist/index.mjs +693 -622
  73. package/dist/styles.css +1 -1
  74. package/package.json +2 -1
@@ -0,0 +1,405 @@
1
+ import {
2
+ __spreadProps,
3
+ __spreadValues
4
+ } from "./chunk-FWCSY2DS.mjs";
5
+
6
+ // app/api/chat-client.ts
7
+ var chatConfig = {};
8
+ function configureChatClient(config) {
9
+ chatConfig.username = config.username;
10
+ chatConfig.password = config.password;
11
+ chatConfig.baseUrl = config.baseUrl;
12
+ }
13
+ function isJson(content) {
14
+ if (typeof content === "object" && content !== null) {
15
+ return Array.isArray(content) || Object.prototype.toString.call(content) === "[object Object]";
16
+ }
17
+ if (typeof content === "string") {
18
+ try {
19
+ const parsed = JSON.parse(content);
20
+ return typeof parsed === "object" && parsed !== null;
21
+ } catch (e) {
22
+ return false;
23
+ }
24
+ }
25
+ return false;
26
+ }
27
+ async function fetchWithErrorHandling(url, options = {}) {
28
+ const headers = new Headers(options.headers);
29
+ headers.set("Content-Type", "application/json");
30
+ if (chatConfig.username && chatConfig.password) {
31
+ headers.set(
32
+ "Authorization",
33
+ "Basic " + btoa(chatConfig.username + ":" + chatConfig.password)
34
+ );
35
+ }
36
+ const finalUrl = chatConfig.baseUrl ? `${chatConfig.baseUrl}${url}` : url;
37
+ let response;
38
+ try {
39
+ response = await fetch(finalUrl, __spreadProps(__spreadValues({}, options), {
40
+ headers
41
+ }));
42
+ } catch (networkError) {
43
+ console.error("Network error:", networkError);
44
+ throw {
45
+ isNetworkError: true,
46
+ message: "Failed to connect to the server. Please check your network.",
47
+ status: 0
48
+ };
49
+ }
50
+ if (!response.ok) {
51
+ let errorBody = {
52
+ message: `API request failed: ${response.status} ${response.statusText}`,
53
+ statusText: response.statusText
54
+ };
55
+ try {
56
+ const contentType2 = response.headers.get("content-type");
57
+ if (contentType2 && contentType2.includes("application/json")) {
58
+ const jsonError = await response.json();
59
+ errorBody = __spreadProps(__spreadValues({}, jsonError), {
60
+ // Include fields like status, message from API
61
+ statusText: response.statusText
62
+ // Keep original statusText
63
+ });
64
+ } else {
65
+ const textError = await response.text();
66
+ errorBody.message = textError || errorBody.message;
67
+ }
68
+ } catch (parseError) {
69
+ console.error("Failed to parse error response body:", parseError);
70
+ }
71
+ throw __spreadProps(__spreadValues({}, errorBody), { status: response.status, isApiError: true });
72
+ }
73
+ const contentType = response.headers.get("content-type");
74
+ if (!contentType || !contentType.includes("application/json")) {
75
+ if (response.status === 204 || !contentType) {
76
+ return { success: true };
77
+ }
78
+ const text = await response.text();
79
+ if (!text.trim()) {
80
+ return { success: true };
81
+ }
82
+ console.warn(
83
+ `API returned non-JSON response for ${url}, status: ${response.status}`
84
+ );
85
+ return { success: true, nonJsonResponse: text };
86
+ }
87
+ return response.json();
88
+ }
89
+ async function createAgentStream(agentId, messages, conversationId, signal, stepData, streaming = true) {
90
+ const lastMessage = messages[messages.length - 1];
91
+ let input = "";
92
+ if (lastMessage && lastMessage.content) {
93
+ if (typeof lastMessage.content === "string") {
94
+ input = lastMessage.content;
95
+ } else if (Array.isArray(lastMessage.content)) {
96
+ const textContent = lastMessage.content.find(
97
+ (c) => c.type === "text"
98
+ );
99
+ if (textContent) {
100
+ input = textContent.text;
101
+ }
102
+ }
103
+ }
104
+ const formData = new FormData();
105
+ formData.append("aiAgent", agentId);
106
+ formData.append("input", input);
107
+ formData.append("stream", streaming ? "true" : "false");
108
+ if (conversationId && conversationId.trim() !== "" && !conversationId.startsWith("temp-")) {
109
+ formData.append("threadID", conversationId);
110
+ }
111
+ if (stepData) {
112
+ formData.append("variables", JSON.stringify(stepData));
113
+ }
114
+ if (lastMessage && Array.isArray(lastMessage.content)) {
115
+ for (const content of lastMessage.content) {
116
+ if (content.type === "image") {
117
+ const imageContent = content;
118
+ const base64Data = imageContent.image.includes(",") ? imageContent.image.split(",")[1] : imageContent.image;
119
+ const byteCharacters = atob(base64Data);
120
+ const byteNumbers = new Array(byteCharacters.length);
121
+ for (let i = 0; i < byteCharacters.length; i++) {
122
+ byteNumbers[i] = byteCharacters.charCodeAt(i);
123
+ }
124
+ const byteArray = new Uint8Array(byteNumbers);
125
+ const blob = new Blob([byteArray], {
126
+ type: imageContent.mediaType
127
+ });
128
+ const file = new File(
129
+ [blob],
130
+ `image.${imageContent.mediaType.split("/")[1]}`,
131
+ {
132
+ type: imageContent.mediaType
133
+ }
134
+ );
135
+ formData.append("files", file);
136
+ } else if (content.type === "file") {
137
+ const fileContent = content;
138
+ const base64Data = fileContent.data.includes(",") ? fileContent.data.split(",")[1] : fileContent.data;
139
+ const byteCharacters = atob(base64Data);
140
+ const byteNumbers = new Array(byteCharacters.length);
141
+ for (let i = 0; i < byteCharacters.length; i++) {
142
+ byteNumbers[i] = byteCharacters.charCodeAt(i);
143
+ }
144
+ const byteArray = new Uint8Array(byteNumbers);
145
+ const blob = new Blob([byteArray], {
146
+ type: fileContent.mediaType
147
+ });
148
+ const file = new File([blob], fileContent.filename, {
149
+ type: fileContent.mediaType
150
+ });
151
+ formData.append("files", file);
152
+ }
153
+ }
154
+ }
155
+ const url = chatConfig.baseUrl ? `${chatConfig.baseUrl}/api/AIBuildersKit/createCompletionAI` : "/api/AIBuildersKit/createCompletionAI";
156
+ const headers = {};
157
+ if (chatConfig.username && chatConfig.password) {
158
+ headers["Authorization"] = "Basic " + btoa(chatConfig.username + ":" + chatConfig.password);
159
+ }
160
+ const response = await fetch(url, {
161
+ method: "POST",
162
+ headers,
163
+ body: formData,
164
+ signal
165
+ });
166
+ if (!response.ok) {
167
+ let errorDetails = `API request failed: ${response.status} ${response.statusText}`;
168
+ try {
169
+ const errorData = await response.json();
170
+ if (errorData && errorData.message) {
171
+ errorDetails = errorData.message;
172
+ }
173
+ } catch (e) {
174
+ }
175
+ throw new Error(errorDetails);
176
+ }
177
+ if (!response.body) {
178
+ throw new Error("Stream not supported by the response");
179
+ }
180
+ return response.body;
181
+ }
182
+ var chatClient = {
183
+ conversations: {
184
+ getAll: async (agentId) => {
185
+ const response = await fetchWithErrorHandling(
186
+ "/api/functions/AIAgent/listUserThreads",
187
+ {
188
+ method: "POST",
189
+ body: JSON.stringify({ agentId })
190
+ }
191
+ );
192
+ if (Array.isArray(response)) {
193
+ return response;
194
+ } else if (response && response.conversations && Array.isArray(response.conversations)) {
195
+ return response.conversations;
196
+ } else if (response && response.data && Array.isArray(response.data)) {
197
+ return response.data;
198
+ } else {
199
+ console.error(
200
+ "Unexpected response format from list-conversations:",
201
+ response
202
+ );
203
+ return [];
204
+ }
205
+ },
206
+ get: async (id) => {
207
+ const response = await fetchWithErrorHandling(
208
+ `/api/functions/AIAgent/getConversation`,
209
+ {
210
+ method: "POST",
211
+ body: JSON.stringify({ id })
212
+ }
213
+ );
214
+ if (Array.isArray(response)) {
215
+ const logs = response;
216
+ const messages = [];
217
+ logs.forEach((log) => {
218
+ let userContent = log.input;
219
+ if (log.files && log.files.length > 0) {
220
+ const contentParts = [];
221
+ if (log.input && log.input.trim()) {
222
+ contentParts.push({
223
+ type: "text",
224
+ text: log.input
225
+ });
226
+ }
227
+ log.files.forEach((file) => {
228
+ if (file.mimeType.startsWith("image/")) {
229
+ contentParts.push({
230
+ type: "image",
231
+ image: `data:${file.mimeType};base64,${file.data}`,
232
+ mediaType: file.mimeType
233
+ });
234
+ } else {
235
+ contentParts.push({
236
+ type: "file",
237
+ data: `data:${file.mimeType};base64,${file.data}`,
238
+ mediaType: file.mimeType,
239
+ filename: file.name
240
+ });
241
+ }
242
+ });
243
+ userContent = contentParts;
244
+ }
245
+ messages.push({
246
+ id: `${log.id}-user`,
247
+ content: userContent,
248
+ role: "user",
249
+ createdAt: log.createdAt
250
+ });
251
+ const assistantMessage = {
252
+ id: `${log.id}-assistant`,
253
+ content: log.output,
254
+ role: "assistant",
255
+ createdAt: log.updatedAt
256
+ };
257
+ if (log.steps && log.steps.length > 0) {
258
+ assistantMessage.metadata = {
259
+ logId: log.id,
260
+ steps: log.steps
261
+ };
262
+ }
263
+ messages.push(assistantMessage);
264
+ });
265
+ const conversation2 = {
266
+ id,
267
+ title: logs.length > 0 ? logs[0].input.substring(0, 50) : "Conversation",
268
+ messages,
269
+ createdAt: logs.length > 0 ? logs[0].createdAt : (/* @__PURE__ */ new Date()).toISOString(),
270
+ updatedAt: logs.length > 0 ? logs[logs.length - 1].updatedAt : (/* @__PURE__ */ new Date()).toISOString()
271
+ };
272
+ return conversation2;
273
+ }
274
+ let conversation;
275
+ if (response && response.id) {
276
+ conversation = response;
277
+ } else if (response && response.conversation) {
278
+ conversation = response.conversation;
279
+ } else if (response && response.data) {
280
+ conversation = response.data;
281
+ } else {
282
+ throw new Error(
283
+ "Unexpected response format from get-conversation"
284
+ );
285
+ }
286
+ if (conversation.messages && Array.isArray(conversation.messages)) {
287
+ conversation.messages = conversation.messages.map((message) => {
288
+ if (message.role === "assistant" && typeof message.content === "string") {
289
+ const content = message.content;
290
+ if (isJson(content) && !content.includes("```json:")) {
291
+ const jsonObj = typeof content === "string" ? JSON.parse(content) : content;
292
+ return __spreadProps(__spreadValues({}, message), {
293
+ content: `\`\`\`json:Response
294
+ ${JSON.stringify(
295
+ jsonObj,
296
+ null,
297
+ 2
298
+ )}
299
+ \`\`\``
300
+ });
301
+ }
302
+ }
303
+ return message;
304
+ });
305
+ }
306
+ return conversation;
307
+ },
308
+ create: async (title, agentId) => {
309
+ return fetchWithErrorHandling(
310
+ `/api/functions/AIAgent/createThread`,
311
+ {
312
+ method: "POST",
313
+ body: JSON.stringify(__spreadValues(__spreadValues({}, title ? { title } : {}), agentId ? { agentId } : {}))
314
+ }
315
+ );
316
+ },
317
+ delete: async (id) => {
318
+ return fetchWithErrorHandling(
319
+ `/api/functions/AIAgent/deleteThreadByIdAndUser`,
320
+ {
321
+ method: "POST",
322
+ body: JSON.stringify({ id })
323
+ }
324
+ );
325
+ },
326
+ update: async (id, data) => {
327
+ return fetchWithErrorHandling(
328
+ `/api/functions/AIAgent/renameThread`,
329
+ {
330
+ method: "POST",
331
+ body: JSON.stringify({ id, title: data.title })
332
+ }
333
+ );
334
+ }
335
+ },
336
+ messages: {
337
+ getLastMessages: async (conversationId, limit = 100) => {
338
+ const conversation = await chatClient.conversations.get(
339
+ conversationId
340
+ );
341
+ return conversation.messages.slice(-limit);
342
+ },
343
+ sendMessage: async (agentId, conversationId, content, existingMessages, signal, debug, stepData, isTemporary, streaming = true) => {
344
+ const idToUse = agentId;
345
+ if (!idToUse || typeof idToUse !== "string" || idToUse.trim() === "") {
346
+ const error = new Error(
347
+ "Assistant or Agent ID is missing or invalid. Please provide a valid Assistant or Agent ID in the URL."
348
+ );
349
+ error.isConfigurationError = true;
350
+ error.status = 400;
351
+ throw error;
352
+ }
353
+ let actualConversationId = conversationId;
354
+ if (isTemporary && agentId) {
355
+ let title = "New Chat";
356
+ if (typeof content === "string") {
357
+ title = content.substring(0, 50);
358
+ } else if (Array.isArray(content)) {
359
+ const textContent = content.find(
360
+ (c) => c.type === "text"
361
+ );
362
+ if (textContent) {
363
+ title = textContent.text.substring(0, 50);
364
+ }
365
+ }
366
+ try {
367
+ const newConversation = await chatClient.conversations.create(title, agentId);
368
+ actualConversationId = newConversation.id;
369
+ } catch (error) {
370
+ console.error("Failed to create conversation:", error);
371
+ throw error;
372
+ }
373
+ }
374
+ const userMessage = {
375
+ role: "user",
376
+ content
377
+ };
378
+ let contextMessages = [];
379
+ if (existingMessages && Array.isArray(existingMessages)) {
380
+ const formattedMessages = existingMessages.map((msg) => ({
381
+ role: msg.role,
382
+ content: msg.content
383
+ }));
384
+ contextMessages = [...formattedMessages, userMessage];
385
+ contextMessages = contextMessages.slice(-10);
386
+ } else {
387
+ contextMessages = [userMessage];
388
+ }
389
+ const stream = await createAgentStream(
390
+ idToUse,
391
+ contextMessages,
392
+ actualConversationId,
393
+ signal,
394
+ stepData,
395
+ streaming
396
+ );
397
+ return { stream, threadId: actualConversationId };
398
+ }
399
+ }
400
+ };
401
+
402
+ export {
403
+ configureChatClient,
404
+ chatClient
405
+ };
@@ -0,0 +1,268 @@
1
+ import {
2
+ __spreadProps,
3
+ __spreadValues
4
+ } from "./chunk-FWCSY2DS.mjs";
5
+
6
+ // app/api/chat-client.ts
7
+ var chatConfig = {};
8
+ function configureChatClient(config) {
9
+ Object.assign(chatConfig, config);
10
+ }
11
+ var base64ToFile = (data, type, name) => {
12
+ const b64 = data.includes(",") ? data.split(",")[1] : data;
13
+ const bin = atob(b64);
14
+ const arr = new Uint8Array(bin.length).map((_, i) => bin.charCodeAt(i));
15
+ return new File([new Blob([arr], { type })], name, { type });
16
+ };
17
+ async function fetchWithErrorHandling(url, options = {}) {
18
+ const headers = new Headers(options.headers);
19
+ headers.set("Content-Type", "application/json");
20
+ if (chatConfig.username && chatConfig.password) {
21
+ headers.set(
22
+ "Authorization",
23
+ "Basic " + btoa(`${chatConfig.username}:${chatConfig.password}`)
24
+ );
25
+ }
26
+ const finalUrl = chatConfig.baseUrl ? `${chatConfig.baseUrl}${url}` : url;
27
+ try {
28
+ const res = await fetch(finalUrl, __spreadProps(__spreadValues({}, options), { headers }));
29
+ const contentType = res.headers.get("content-type");
30
+ const isJson = contentType == null ? void 0 : contentType.includes("application/json");
31
+ if (!res.ok) {
32
+ const err = isJson ? await res.json() : { message: await res.text() };
33
+ throw __spreadProps(__spreadValues({}, err), {
34
+ status: res.status,
35
+ statusText: res.statusText,
36
+ isApiError: true
37
+ });
38
+ }
39
+ if (res.status === 204 || !contentType) return { success: true };
40
+ return isJson ? res.json() : { success: true, nonJsonResponse: await res.text() };
41
+ } catch (error) {
42
+ if (error.isApiError) throw error;
43
+ throw {
44
+ isNetworkError: true,
45
+ message: "Network connection failed",
46
+ status: 0,
47
+ originalError: error
48
+ };
49
+ }
50
+ }
51
+ async function createAgentStream(agentId, messages, conversationId, signal, stepData, streaming = true) {
52
+ var _a;
53
+ const lastMsg = messages[messages.length - 1];
54
+ let input = "";
55
+ if (typeof (lastMsg == null ? void 0 : lastMsg.content) === "string") input = lastMsg.content;
56
+ else if (Array.isArray(lastMsg == null ? void 0 : lastMsg.content))
57
+ input = ((_a = lastMsg.content.find((c) => c.type === "text")) == null ? void 0 : _a.text) || "";
58
+ const formData = new FormData();
59
+ formData.append("aiAgent", agentId);
60
+ formData.append("input", input);
61
+ formData.append("stream", String(streaming));
62
+ if (conversationId && !conversationId.startsWith("temp-"))
63
+ formData.append("threadID", conversationId);
64
+ if (stepData) formData.append("variables", JSON.stringify(stepData));
65
+ if (Array.isArray(lastMsg == null ? void 0 : lastMsg.content)) {
66
+ lastMsg.content.forEach((c) => {
67
+ if (c.type === "image")
68
+ formData.append(
69
+ "files",
70
+ base64ToFile(
71
+ c.image,
72
+ c.mediaType,
73
+ `image.${c.mediaType.split("/")[1]}`
74
+ )
75
+ );
76
+ else if (c.type === "file")
77
+ formData.append(
78
+ "files",
79
+ base64ToFile(c.data, c.mediaType, c.filename)
80
+ );
81
+ });
82
+ }
83
+ const url = chatConfig.baseUrl ? `${chatConfig.baseUrl}/api/AIBuildersKit/createCompletionAI` : "/api/AIBuildersKit/createCompletionAI";
84
+ const headers = chatConfig.username ? {
85
+ Authorization: "Basic " + btoa(`${chatConfig.username}:${chatConfig.password}`)
86
+ } : {};
87
+ const response = await fetch(url, {
88
+ method: "POST",
89
+ headers,
90
+ body: formData,
91
+ signal
92
+ });
93
+ if (!response.ok)
94
+ throw new Error(
95
+ (await response.json().catch(() => ({}))).message || response.statusText
96
+ );
97
+ if (!response.body) throw new Error("Stream not supported");
98
+ return response.body;
99
+ }
100
+ var chatClient = {
101
+ conversations: {
102
+ getAll: async (agentId) => {
103
+ const res = await fetchWithErrorHandling(
104
+ "/api/functions/AIAgent/listUserThreads",
105
+ { method: "POST", body: JSON.stringify({ agentId }) }
106
+ );
107
+ return Array.isArray(res) ? res : res.conversations || res.data || [];
108
+ },
109
+ get: async (id) => {
110
+ var _a, _b, _c;
111
+ const res = await fetchWithErrorHandling(
112
+ `/api/functions/AIAgent/getConversation`,
113
+ { method: "POST", body: JSON.stringify({ id }) }
114
+ );
115
+ if (Array.isArray(res)) {
116
+ const messages = res.flatMap((log) => {
117
+ var _a2, _b2, _c2, _d;
118
+ let userContent = log.input;
119
+ if ((_a2 = log.files) == null ? void 0 : _a2.length) {
120
+ userContent = [
121
+ ...((_b2 = log.input) == null ? void 0 : _b2.trim()) ? [
122
+ {
123
+ type: "text",
124
+ text: log.input
125
+ }
126
+ ] : [],
127
+ ...log.files.map(
128
+ (f) => f.mimeType.startsWith("image/") ? {
129
+ type: "image",
130
+ image: `data:${f.mimeType};base64,${f.data}`,
131
+ mediaType: f.mimeType
132
+ } : {
133
+ type: "file",
134
+ data: `data:${f.mimeType};base64,${f.data}`,
135
+ mediaType: f.mimeType,
136
+ filename: f.name
137
+ }
138
+ )
139
+ ];
140
+ }
141
+ const asstMsg = {
142
+ id: `${log.id}-assistant`,
143
+ content: log.output,
144
+ role: "assistant",
145
+ createdAt: log.updatedAt
146
+ };
147
+ if (((_c2 = log.steps) == null ? void 0 : _c2.length) || ((_d = log.vectors) == null ? void 0 : _d.length) || log.feedbackPositive !== void 0) {
148
+ asstMsg.metadata = {
149
+ logId: log.id,
150
+ steps: log.steps,
151
+ vectors: log.vectors,
152
+ feedbackPositive: log.feedbackPositive
153
+ };
154
+ }
155
+ return [
156
+ {
157
+ id: `${log.id}-user`,
158
+ content: userContent,
159
+ role: "user",
160
+ createdAt: log.createdAt
161
+ },
162
+ asstMsg
163
+ ];
164
+ });
165
+ return {
166
+ id,
167
+ title: ((_a = res[0]) == null ? void 0 : _a.input.substring(0, 50)) || "Conversation",
168
+ messages,
169
+ createdAt: ((_b = res[0]) == null ? void 0 : _b.createdAt) || (/* @__PURE__ */ new Date()).toISOString(),
170
+ updatedAt: ((_c = res[res.length - 1]) == null ? void 0 : _c.updatedAt) || (/* @__PURE__ */ new Date()).toISOString()
171
+ };
172
+ }
173
+ const conv = res.conversation || res.data || res;
174
+ if (conv.messages) {
175
+ conv.messages = conv.messages.map((m) => {
176
+ if (m.role === "assistant" && typeof m.content === "string") {
177
+ try {
178
+ const parsed = JSON.parse(m.content);
179
+ if (typeof parsed === "object" && parsed !== null && !m.content.includes("```json:")) {
180
+ return __spreadProps(__spreadValues({}, m), {
181
+ content: `\`\`\`json:Response
182
+ ${JSON.stringify(
183
+ parsed,
184
+ null,
185
+ 2
186
+ )}
187
+ \`\`\``
188
+ });
189
+ }
190
+ } catch (e) {
191
+ }
192
+ }
193
+ return m;
194
+ });
195
+ }
196
+ return conv;
197
+ },
198
+ create: (title, agentId) => fetchWithErrorHandling(`/api/functions/AIAgent/createThread`, {
199
+ method: "POST",
200
+ body: JSON.stringify(__spreadValues(__spreadValues({}, title && { title }), agentId && { agentId }))
201
+ }),
202
+ delete: (id) => fetchWithErrorHandling(
203
+ `/api/functions/AIAgent/deleteThreadByIdAndUser`,
204
+ { method: "POST", body: JSON.stringify({ id }) }
205
+ ),
206
+ update: (id, data) => fetchWithErrorHandling(`/api/functions/AIAgent/renameThread`, {
207
+ method: "POST",
208
+ body: JSON.stringify({ id, title: data.title })
209
+ })
210
+ },
211
+ messages: {
212
+ getLastMessages: async (conversationId, limit = 100) => (await chatClient.conversations.get(conversationId)).messages.slice(
213
+ -limit
214
+ ),
215
+ sendMessage: async (agentId, conversationId, content, existingMessages, signal, stepData, isTemporary, streaming = true) => {
216
+ var _a;
217
+ if (!agentId)
218
+ throw {
219
+ isConfigurationError: true,
220
+ status: 400,
221
+ message: "Assistant ID missing"
222
+ };
223
+ let actualId = conversationId;
224
+ let createdConv;
225
+ if (isTemporary && agentId) {
226
+ const titleText = typeof content === "string" ? content : ((_a = content.find(
227
+ (c) => c.type === "text"
228
+ )) == null ? void 0 : _a.text) || "";
229
+ createdConv = await chatClient.conversations.create(
230
+ titleText.substring(0, 50) || "New Chat",
231
+ agentId
232
+ );
233
+ actualId = createdConv.id;
234
+ }
235
+ const context = [
236
+ ...(existingMessages == null ? void 0 : existingMessages.map((m) => ({
237
+ role: m.role,
238
+ content: m.content
239
+ }))) || [],
240
+ { role: "user", content }
241
+ ].slice(-10);
242
+ return {
243
+ stream: await createAgentStream(
244
+ agentId,
245
+ context,
246
+ actualId,
247
+ signal,
248
+ stepData,
249
+ streaming
250
+ ),
251
+ threadId: actualId,
252
+ conversation: createdConv
253
+ };
254
+ }
255
+ },
256
+ feedback: {
257
+ submit: (id, feedbackPositive, aiAgent) => fetchWithErrorHandling("/api/AIBuildersKit/giveAgentFeedbackAI", {
258
+ method: "POST",
259
+ headers: { "Content-Type": "application/json" },
260
+ body: JSON.stringify({ id, feedbackPositive, aiAgent })
261
+ })
262
+ }
263
+ };
264
+
265
+ export {
266
+ configureChatClient,
267
+ chatClient
268
+ };