@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.
- package/README.md +2 -22
- package/dist/chat-input-2CHIBULE.mjs +510 -0
- package/dist/chat-input-G2LRENLB.mjs +512 -0
- package/dist/chat-input-IIV2HQOZ.mjs +509 -0
- package/dist/chat-input-MLF62KV7.mjs +512 -0
- package/dist/chat-input-MOPCNDRR.mjs +517 -0
- package/dist/chat-input-TYNO3J5S.mjs +519 -0
- package/dist/chat-input-VQZ3WNBT.mjs +509 -0
- package/dist/chat-input-ZAFYBUO7.mjs +507 -0
- package/dist/chat-message-EQTB6N5X.mjs +2306 -0
- package/dist/chat-message-GUOL4RZU.mjs +2306 -0
- package/dist/chat-message-HWBFOYOJ.mjs +2306 -0
- package/dist/chat-message-NZNZX6VS.mjs +2306 -0
- package/dist/chunk-VONUV37R.mjs +268 -0
- package/dist/chunk-XQVUOR36.mjs +438 -0
- package/dist/chunk-Y7QF5535.mjs +268 -0
- package/dist/index.d.mts +1 -6
- package/dist/index.d.ts +1 -6
- package/dist/index.js +319 -614
- package/dist/index.mjs +124 -246
- package/package.json +1 -1
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,438 @@
|
|
|
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 || log.vectors && log.vectors.length > 0 || log.feedbackPositive !== void 0) {
|
|
258
|
+
assistantMessage.metadata = {
|
|
259
|
+
logId: log.id,
|
|
260
|
+
steps: log.steps,
|
|
261
|
+
vectors: log.vectors,
|
|
262
|
+
feedbackPositive: log.feedbackPositive
|
|
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
|
+
let createdConversation = void 0;
|
|
357
|
+
if (isTemporary && agentId) {
|
|
358
|
+
let title = "New Chat";
|
|
359
|
+
if (typeof content === "string") {
|
|
360
|
+
title = content.substring(0, 50);
|
|
361
|
+
} else if (Array.isArray(content)) {
|
|
362
|
+
const textContent = content.find(
|
|
363
|
+
(c) => c.type === "text"
|
|
364
|
+
);
|
|
365
|
+
if (textContent) {
|
|
366
|
+
title = textContent.text.substring(0, 50);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
const newConversation = await chatClient.conversations.create(title, agentId);
|
|
371
|
+
actualConversationId = newConversation.id;
|
|
372
|
+
createdConversation = newConversation;
|
|
373
|
+
} catch (error) {
|
|
374
|
+
console.error("Failed to create conversation:", error);
|
|
375
|
+
throw error;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const userMessage = {
|
|
379
|
+
role: "user",
|
|
380
|
+
content
|
|
381
|
+
};
|
|
382
|
+
let contextMessages = [];
|
|
383
|
+
if (existingMessages && Array.isArray(existingMessages)) {
|
|
384
|
+
const formattedMessages = existingMessages.map((msg) => ({
|
|
385
|
+
role: msg.role,
|
|
386
|
+
content: msg.content
|
|
387
|
+
}));
|
|
388
|
+
contextMessages = [...formattedMessages, userMessage];
|
|
389
|
+
contextMessages = contextMessages.slice(-10);
|
|
390
|
+
} else {
|
|
391
|
+
contextMessages = [userMessage];
|
|
392
|
+
}
|
|
393
|
+
const stream = await createAgentStream(
|
|
394
|
+
idToUse,
|
|
395
|
+
contextMessages,
|
|
396
|
+
actualConversationId,
|
|
397
|
+
signal,
|
|
398
|
+
stepData,
|
|
399
|
+
streaming
|
|
400
|
+
);
|
|
401
|
+
return {
|
|
402
|
+
stream,
|
|
403
|
+
threadId: actualConversationId,
|
|
404
|
+
conversation: createdConversation
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
},
|
|
408
|
+
feedback: {
|
|
409
|
+
/**
|
|
410
|
+
* Submit feedback for an AI response
|
|
411
|
+
* @param logId - The ID of the log/message
|
|
412
|
+
* @param feedbackPositive - true for like, false for dislike
|
|
413
|
+
* @param aiAgent - The agent ID
|
|
414
|
+
*/
|
|
415
|
+
submit: async (logId, feedbackPositive, aiAgent) => {
|
|
416
|
+
const response = await fetchWithErrorHandling(
|
|
417
|
+
"/api/AIBuildersKit/giveAgentFeedbackAI",
|
|
418
|
+
{
|
|
419
|
+
method: "POST",
|
|
420
|
+
headers: {
|
|
421
|
+
"Content-Type": "application/json"
|
|
422
|
+
},
|
|
423
|
+
body: JSON.stringify({
|
|
424
|
+
id: logId,
|
|
425
|
+
feedbackPositive,
|
|
426
|
+
aiAgent
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
);
|
|
430
|
+
return response;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
export {
|
|
436
|
+
configureChatClient,
|
|
437
|
+
chatClient
|
|
438
|
+
};
|