@terryavg/neptune-ai-chatbot 1.0.1 → 1.0.2

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