anything-llm-web-ai-assistant-script

ai-assistant.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
* AI Assistant Widget
* 一个可嵌入网站的AI助手小部件,使用Anything LLM API
*/

(function (global) {
// 导出AIAssistant类
function initAIAssistant(config) {
return new AIAssistant(config);
}

// 将初始化函数暴露给全局对象
global.initAIAssistant = initAIAssistant;
// 配置选项
const DEFAULT_CONFIG = {
botName: "AI助手",
welcomeMessage: "你好!我是AI助手,有什么可以帮到你的吗?",
primaryColor: "#333",
apiEndpoint: "http://localhost:3001/v1/workspace", // Anything LLM默认API端点
apiKey: "G601NFG-YY1M8F5-JEQPMR5-VQJGB11", // 用户需要设置自己的API密钥
position: "right", // 悬浮按钮位置:'right'或'left'
slug: "testworking", // 工作区标识
};

// 创建并初始化AI助手
class AIAssistant {
constructor(config = {}) {
this.config = { ...DEFAULT_CONFIG, ...config };
this.isOpen = false;
this.isWaitingForResponse = false;

this.init();
}

init() {
this.loadDependencies()
.then(() => {
this.createStyles();
this.createWidgetElements();
this.setupEventListeners();
})
.catch((error) => {
console.error("AI助手初始化失败:", error);
});
// session id
this.sessionId = this.generateSessionId();
}
// 生成唯一的会话ID
generateSessionId() {
// 使用UUID v4算法生成唯一ID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}

// 加载外部依赖
loadDependencies() {
return new Promise((resolve, reject) => {
// 加载markdown-it库
if (window.markdownit) {
this.md = window.markdownit();
resolve();
return;
}
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/npm/markdown-it/dist/markdown-it.min.js";
script.onload = () => {
this.md = window.markdownit();
resolve();
};
script.onerror = () => reject(new Error("无法加载markdown-it库"));
document.head.appendChild(script);
});
}

// 创建样式
createStyles() {
const { primaryColor } = this.config;
const styleEl = document.createElement("style");
styleEl.innerHTML = `
.ai-assistant-widget {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-size: 16px;
line-height: 1.5;
color: #333;
box-sizing: border-box;
}

.ai-assistant-widget * {
box-sizing: border-box;
}

.ai-assistant-button {
position: fixed;
bottom: 20px;
${this.config.position === "right" ? "right: 20px;" : "left: 20px;"}
width: 60px;
height: 60px;
border-radius: 50%;
background-color: ${primaryColor};
color: white;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
transition: all 0.3s ease;
z-index: 9999;
}

.ai-assistant-button:hover {
transform: scale(1.05);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.25);
}

.ai-assistant-chat-container p {
margin: 0;
}

.ai-assistant-chat-container think {
color: #666;
font-size: 12px;
margin-bottom: 10px;
}
.ai-assistant-chat-container think::before {
content: '...'
}
.ai-assistant-chat-container think::after {
content: '...'
}

.ai-assistant-icon {
width: 30px;
height: 30px;
}

.ai-assistant-chat-container {
position: fixed;
bottom: 90px;
${this.config.position === "right" ? "right: 20px;" : "left: 20px;"}
max-width: 500px;
height: 86vh;
background-color: white;
border-radius: 10px;
box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
display: flex;
flex-direction: column;
overflow: hidden;
z-index: 9999;
transition: all 0.3s ease;
opacity: 0;
transform: translateY(20px);
pointer-events: none;
}

.ai-assistant-chat-container.open {
opacity: 1;
transform: translateY(0);
pointer-events: all;
}

.ai-assistant-header {
padding: 15px;
background-color: ${primaryColor};
color: white;
font-weight: bold;
display: flex;
justify-content: space-between;
align-items: center;
}

.ai-assistant-close-btn {
background: none;
border: none;
color: white;
font-size: 20px;
cursor: pointer;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
}



.ai-assistant-messages {
flex: 1;
overflow-y: auto;
padding: 15px;
display: flex;
flex-direction: column;
gap: 15px;
}

.ai-assistant-message {
max-width: 80%;
padding: 10px 15px;
border-radius: 18px;
word-break: break-word;
font-size: 14px;
}

.ai-assistant-message.user {
align-self: flex-end;
background-color: ${primaryColor};
color: white;
border-bottom-right-radius: 5px;
}

.ai-assistant-message.bot {
align-self: flex-start;
background-color: #f1f1f1;
border-bottom-left-radius: 5px;
}

.ai-assistant-message.bot a {
color: ${primaryColor};
text-decoration: underline;
}

.ai-assistant-message.bot pre {
background-color: #f8f8f8;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
overflow-x: auto;
margin: 10px 0;
}

.ai-assistant-message.bot code {
font-family: fangsong;
padding: 2px 4px;
border-radius: 3px;
}

.ai-assistant-input-container {
display: flex;
padding: 10px;
border-top: 1px solid #eee;
background-color: white;
}

.ai-assistant-input {
flex: 1;
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 6px;
outline: none;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-size: 15px;
line-height: 1.5;
font-weight: normal;
resize: none;
max-height: 120px;
overflow-y: auto;
}

.ai-assistant-input:focus {
border-color: ${primaryColor};
}

.ai-assistant-send-btn {
width: 44px;
height: 44px;
border-radius: 50%;
background-color: ${primaryColor};
color: white;
border: none;
margin-left: 10px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
}

.ai-assistant-send-btn:hover {
background-color: ${this.adjustColor(primaryColor, -20)};
}

.ai-assistant-send-btn:disabled {
background-color: #ccc;
cursor: not-allowed;
}

.ai-assistant-typing-indicator {
display: flex;
align-items: center;
padding: 10px 15px;
background-color: #f1f1f1;
border-radius: 18px;
border-bottom-left-radius: 5px;
align-self: flex-start;
margin-bottom: 10px;
}

.ai-assistant-typing-indicator span {
width: 8px;
height: 8px;
background-color: #888;
border-radius: 50%;
display: inline-block;
margin: 0 2px;
animation: ai-assistant-typing 1.4s infinite ease-in-out both;
}

.ai-assistant-typing-indicator span:nth-child(1) {
animation-delay: -0.32s;
}

.ai-assistant-typing-indicator span:nth-child(2) {
animation-delay: -0.16s;
}

@keyframes ai-assistant-typing {
0%, 80%, 100% { transform: scale(0); }
40% { transform: scale(1); }
}

@media (max-width: 480px) {
.ai-assistant-chat-container {
width: calc(100% - 40px);
height: 60vh;
}
}
`;
document.head.appendChild(styleEl);
}

// 创建小部件元素
createWidgetElements() {
// 创建悬浮按钮
this.button = document.createElement("div");
this.button.className = "ai-assistant-button ai-assistant-widget";
this.button.innerHTML = `
<svg class="ai-assistant-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM16 13H13V16C13 16.55 12.55 17 12 17C11.45 17 11 16.55 11 16V13H8C7.45 13 7 12.55 7 12C7 11.45 7.45 11 8 11H11V8C11 7.45 11.45 7 12 7C12.55 7 13 7.45 13 8V11H16C16.55 11 17 11.45 17 12C17 12.55 16.55 13 16 13Z" fill="white"/>
</svg>
`;
document.body.appendChild(this.button);

// 创建聊天容器
this.chatContainer = document.createElement("div");
this.chatContainer.className =
"ai-assistant-chat-container ai-assistant-widget";
this.chatContainer.innerHTML = `
<div class="ai-assistant-header">
<div>${this.config.botName}</div>
<button class="ai-assistant-close-btn">&times;</button>
</div>
<div class="ai-assistant-messages"></div>
<div class="ai-assistant-input-container">
<textarea class="ai-assistant-input" placeholder="输入消息..." rows="2"></textarea>
<button class="ai-assistant-send-btn">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.01 21L23 12L2.01 3L2 10L17 12L2 14L2.01 21Z" fill="white"/>
</svg>
</button>
</div>
`;
document.body.appendChild(this.chatContainer);

// 获取元素引用
this.messagesContainer = this.chatContainer.querySelector(
".ai-assistant-messages"
);
this.inputElement = this.chatContainer.querySelector(
".ai-assistant-input"
);
this.sendButton = this.chatContainer.querySelector(
".ai-assistant-send-btn"
);
this.closeButton = this.chatContainer.querySelector(
".ai-assistant-close-btn"
);

// 添加欢迎消息
this.addMessage(this.config.welcomeMessage, "bot");
}

// 设置事件监听器
setupEventListeners() {
// 打开/关闭聊天窗口
this.button.addEventListener("click", () => this.toggleChat());
this.closeButton.addEventListener("click", () => this.toggleChat(false));

// 发送消息
this.sendButton.addEventListener("click", () => this.sendMessage());
this.inputElement.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});

// 自动调整输入框高度
this.inputElement.addEventListener("input", () => {
this.inputElement.style.height = "auto";
this.inputElement.style.height =
Math.min(this.inputElement.scrollHeight, 120) + "px";
});
}

// 切换聊天窗口
toggleChat(open = null) {
this.isOpen = open !== null ? open : !this.isOpen;
if (this.isOpen) {
this.chatContainer.classList.add("open");
this.inputElement.focus();
// 滚动到底部
this.scrollToBottom();
} else {
this.chatContainer.classList.remove("open");
}
}

// 添加消息到聊天窗口
addMessage(content, type) {
const messageEl = document.createElement("div");
messageEl.className = `ai-assistant-message ${type}`;

if (type === "bot") {
// 使用markdown-it渲染Markdown内容
messageEl.innerHTML = this.md.render(content);
} else {
messageEl.textContent = content;
}
this.messagesContainer.appendChild(messageEl);
this.scrollToBottom();
}

// 显示正在输入指示器
showTypingIndicator() {
const typingEl = document.createElement("div");
typingEl.className = "ai-assistant-typing-indicator";
typingEl.innerHTML = "<span></span><span></span><span></span>";
typingEl.id = "ai-assistant-typing";
this.messagesContainer.appendChild(typingEl);
this.scrollToBottom();
}

// 隐藏正在输入指示器
hideTypingIndicator() {
const typingEl = document.getElementById("ai-assistant-typing");
if (typingEl) {
typingEl.remove();
}
}

// 发送消息到AI
sendMessage() {
const message = this.inputElement.value.trim();
if (!message || this.isWaitingForResponse) return;

// 清空输入框
this.inputElement.value = "";
// 添加用户消息到聊天窗口
this.addMessage(message, "user");

// 禁用发送按钮并显示正在输入指示器
this.isWaitingForResponse = true;
this.sendButton.disabled = true;
this.showTypingIndicator();
// 发送请求到Anything LLM API

this.sendToAPI(message, this.onMessageReceived, this.onMessageEnd);
}

onMessageEnd(_this) {
_this.isWaitingForResponse = false;
_this.sendButton.disabled = false;
}

onMessageReceived(_this, ele, message) {
_this.hideTypingIndicator();
_this.scrollToBottom();
if (message && message.textResponse) {
_this.messageText += message.textResponse;
}

const res = _this.md.render(_this.messageText).replaceAll('<p>', '').replaceAll('</p>', '').replace('&lt;think&gt;', '<think>').replace('&lt;/think&gt;', '</think><br /><br />')

ele.innerHTML = res;
}

// 发送请求到API
// 发送请求到API(支持流式响应)
async sendToAPI(message, onMessageReceived, onEnd) {
const { apiEndpoint, apiKey } = this.config;
if (this.config.adv.eleId && this.config.adv.appendText) {
const kwd = document.getElementById(this.config.adv.eleId);
message += this.config.adv.appendText + kwd.innerText;
}

try {
const response = await fetch(apiEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
},
body: JSON.stringify({
message,
mode: "query",
sessionId: this.sessionId,
}),
});
const streamMessage = document.createElement("div");
streamMessage.className = "ai-assistant-message bot";
this.messagesContainer.appendChild(streamMessage);
this.messageText = "";

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

while (true) {
const { done, value } = await reader.read();
if (done) {
onEnd(this);
break;
}

buffer += decoder.decode(value, { stream: true });

// 按行处理数据
const lines = buffer.split("\n");
buffer = lines.pop();

lines.forEach((line) => {
if (line.trim().length > 0) {
// 处理每行数据
const eventParts = line.split(":");
const eventType = eventParts[0].trim();
const eventData = eventParts.slice(1).join(":").trim();

if (eventType === "data") {
try {
const message = JSON.parse(eventData);
onMessageReceived(this, streamMessage, message);
} catch (e) {
console.error("Error parsing message:", e);
}
}
}
});
}
} catch (error) {
console.error("API请求错误:", error);
this.hideTypingIndicator();
this.addMessage("抱歉,我遇到了一些问题,无法回答您的问题。", "bot");
this.isWaitingForResponse = false;
this.sendButton.disabled = false;
}
}

// 滚动到底部
scrollToBottom() {
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
}

// 调整颜色亮度
adjustColor(color, amount) {
return (
"#" +
color.replace(/^#/, "").replace(/../g, (color) => {
const num = parseInt(color, 16);
const r = Math.min(Math.max(0, num + amount), 255).toString(16);
return r.length < 2 ? "0" + r : r;
})
);
}
}
})(window);

示例

example.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI助手示例</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
line-height: 1.6;
color: #333;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: #4a90e2;
border-bottom: 2px solid #eee;
padding-bottom: 10px;
}
.code-block {
background-color: #f5f5f5;
border-radius: 5px;
padding: 15px;
overflow-x: auto;
margin: 20px 0;
}
pre {
margin: 0;
}
.note {
background-color: #fffde7;
border-left: 4px solid #ffd600;
padding: 15px;
margin: 20px 0;
}
</style>
</head>
<body>

<div id="quotation">

<div style="font-size: 24px; font-weight: bold;">TEST报价单</div>
<div style="margin: 10px 0; font-weight: bold;">输入参数</div>
<div>
<span>电芯选择: </span> <span>宁德时代 202503</span>
</div>


<div style="margin: 10px 0; font-weight: bold;">报价单</div>

<table border="1px">
<tr>
<td>报价项</td>
<td>数量</td>
<td>总价</td>
</tr>
<tr>
<td>PCS</td>
<td>12</td>
<td>1500</td>
</tr>
<tr>
<td>PACK</td>
<td>48</td>
<td>5000</td>
</tr>
<tr>
<td>一次电气组件</td>
<td>12</td>
<td>3000</td>
</tr>
<tr>
<td>抽检样品</td>
<td>2</td>
<td>20000</td>
</tr>
</table>
</div>

<script src="ai-assistant.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
// 初始化AI助手
const assistant = initAIAssistant({
botName: '网站助手',
welcomeMessage: '你好!这是一个AI助手,你可以在这里测试功能。',
primaryColor: '#000',
apiEndpoint: 'http://localhost:3001/api/v1/workspace/test/stream-chat', // 替换为您的API端点
apiKey: 'G601NFG-YY1M8F5-JEQPMR5-VQJGB11', // 替换为您的API密钥
position: 'right',
adv: {
eleId: 'quotation',
appendText: ' \n(以下内容为提示:提供此上下文信息,请自行判断用户询问是否与此有关联,若无关联,则不要思考此信息。 以下为报价单详情:'
}
});
});
</script>
</body>
</html>