@terryavg/neptune-ai-chatbot 1.0.2 → 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.
@@ -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, debug, 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
+ };
package/dist/index.d.mts CHANGED
@@ -31,11 +31,6 @@ interface NeptuneChatBotProps {
31
31
  * @required
32
32
  */
33
33
  agentId: string;
34
- /**
35
- * Enable debug mode to show console logs and debugging information
36
- * @default false
37
- */
38
- debug?: boolean;
39
34
  /**
40
35
  * Color theme for the chat interface
41
36
  * @default "light"
@@ -220,7 +215,7 @@ interface NeptuneChatBotProps {
220
215
  */
221
216
  onFinish?: (metadata: any) => void;
222
217
  }
223
- declare function NeptuneChatBot({ agentId: propAgentId, debug: propDebug, theme: propTheme, localDebug: propLocalDebug, title: propTitle, messageBubbleColor, messageBubbleColorDark, accentColor, accentColorDark, scrollButtonColor, scrollButtonColorDark, streamingText, streamingTextColor, streamingTextColorDark, welcomeMessagePrimary, welcomeMessageSecondary, welcomeIcon, welcomeIconSize, streaming, sidebarBackgroundColor, onToolStart, onToolInput, onToolFinish, onChunk, onFinish, sidebarBackgroundColorDark, inputBackgroundColor, inputBackgroundColorDark, headerBackgroundColor, headerBackgroundColorDark, vectorColor, vectorColorDark, }: NeptuneChatBotProps): react_jsx_runtime.JSX.Element;
218
+ declare function NeptuneChatBot({ agentId: propAgentId, theme: propTheme, localDebug: propLocalDebug, title: propTitle, messageBubbleColor, messageBubbleColorDark, accentColor, accentColorDark, scrollButtonColor, scrollButtonColorDark, streamingText, streamingTextColor, streamingTextColorDark, welcomeMessagePrimary, welcomeMessageSecondary, welcomeIcon, welcomeIconSize, streaming, sidebarBackgroundColor, onToolStart, onToolInput, onToolFinish, onChunk, onFinish, sidebarBackgroundColorDark, inputBackgroundColor, inputBackgroundColorDark, headerBackgroundColor, headerBackgroundColorDark, vectorColor, vectorColorDark, }: NeptuneChatBotProps): react_jsx_runtime.JSX.Element;
224
219
 
225
220
  interface TextContent {
226
221
  type: "text";
package/dist/index.d.ts CHANGED
@@ -31,11 +31,6 @@ interface NeptuneChatBotProps {
31
31
  * @required
32
32
  */
33
33
  agentId: string;
34
- /**
35
- * Enable debug mode to show console logs and debugging information
36
- * @default false
37
- */
38
- debug?: boolean;
39
34
  /**
40
35
  * Color theme for the chat interface
41
36
  * @default "light"
@@ -220,7 +215,7 @@ interface NeptuneChatBotProps {
220
215
  */
221
216
  onFinish?: (metadata: any) => void;
222
217
  }
223
- declare function NeptuneChatBot({ agentId: propAgentId, debug: propDebug, theme: propTheme, localDebug: propLocalDebug, title: propTitle, messageBubbleColor, messageBubbleColorDark, accentColor, accentColorDark, scrollButtonColor, scrollButtonColorDark, streamingText, streamingTextColor, streamingTextColorDark, welcomeMessagePrimary, welcomeMessageSecondary, welcomeIcon, welcomeIconSize, streaming, sidebarBackgroundColor, onToolStart, onToolInput, onToolFinish, onChunk, onFinish, sidebarBackgroundColorDark, inputBackgroundColor, inputBackgroundColorDark, headerBackgroundColor, headerBackgroundColorDark, vectorColor, vectorColorDark, }: NeptuneChatBotProps): react_jsx_runtime.JSX.Element;
218
+ declare function NeptuneChatBot({ agentId: propAgentId, theme: propTheme, localDebug: propLocalDebug, title: propTitle, messageBubbleColor, messageBubbleColorDark, accentColor, accentColorDark, scrollButtonColor, scrollButtonColorDark, streamingText, streamingTextColor, streamingTextColorDark, welcomeMessagePrimary, welcomeMessageSecondary, welcomeIcon, welcomeIconSize, streaming, sidebarBackgroundColor, onToolStart, onToolInput, onToolFinish, onChunk, onFinish, sidebarBackgroundColorDark, inputBackgroundColor, inputBackgroundColorDark, headerBackgroundColor, headerBackgroundColorDark, vectorColor, vectorColorDark, }: NeptuneChatBotProps): react_jsx_runtime.JSX.Element;
224
219
 
225
220
  interface TextContent {
226
221
  type: "text";