-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathweb_test_server.py
More file actions
1009 lines (858 loc) · 32.4 KB
/
web_test_server.py
File metadata and controls
1009 lines (858 loc) · 32.4 KB
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Bot测试Web服务器
提供Web界面测试bot的回复质量、人格系统和RAG功能
"""
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
from datetime import datetime
import sys
import json
import logging
from io import StringIO
from chatbot.utils.config import Config
from chatbot.db.message_db import MessageDB
from chatbot.handlers.ai_interface import AIInterface
from openai import AzureOpenAI
app = Flask(__name__)
CORS(app)
# 自定义日志捕获器
class LogCapture(logging.Handler):
def __init__(self):
super().__init__()
self.logs = []
def emit(self, record):
try:
log_entry = self.format(record)
self.logs.append(log_entry)
except Exception:
pass
def get_logs(self):
return self.logs.copy()
def clear(self):
self.logs.clear()
# 初始化组件
config = Config()
message_db = MessageDB(config)
# 初始化AI客户端
azure_config = config.get_azure_config()
openai_client = AzureOpenAI(
azure_endpoint=azure_config['openai_endpoint'],
api_key=azure_config['openai_key'],
api_version=azure_config['api_version']
)
# 初始化AI接口
ai_interface = AIInterface(config, openai_client, message_db)
# 用于捕获prompt的全局变量
last_prompt_info = {}
# HTML模板
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bot测试平台 - 带Prompt日志</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1800px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 5px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.header p {
font-size: 1.1em;
opacity: 0.9;
}
.main-content {
display: flex;
height: calc(100vh - 200px);
}
.sidebar {
width: 260px;
background: #f8f9fa;
border-right: 1px solid #e9ecef;
padding: 20px;
overflow-y: auto;
}
.sidebar h3 {
color: #495057;
margin-bottom: 15px;
font-size: 1.1em;
}
.persona-list {
list-style: none;
}
.persona-item {
padding: 10px;
margin-bottom: 6px;
background: white;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
border: 2px solid transparent;
font-size: 0.9em;
}
.persona-item:hover {
transform: translateX(5px);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.persona-item.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.persona-emoji {
font-size: 1.3em;
margin-right: 6px;
}
.test-mode {
margin-top: 15px;
padding: 12px;
background: white;
border-radius: 8px;
}
.test-mode label {
display: block;
margin-bottom: 8px;
color: #495057;
font-weight: 500;
font-size: 0.9em;
}
.test-mode select {
width: 100%;
padding: 8px;
border: 1px solid #ced4da;
border-radius: 6px;
font-size: 0.9em;
}
.chat-area {
flex: 1;
display: flex;
flex-direction: column;
padding: 20px;
min-width: 0;
}
.log-area {
width: 450px;
background: #1e1e1e;
border-left: 1px solid #e9ecef;
padding: 20px;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.log-header {
color: #fff;
font-size: 1.2em;
font-weight: bold;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 2px solid #667eea;
}
.log-content {
flex: 1;
overflow-y: auto;
font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
font-size: 0.85em;
line-height: 1.6;
}
.log-entry {
margin-bottom: 20px;
padding: 15px;
background: #2d2d2d;
border-radius: 8px;
border-left: 3px solid #667eea;
animation: slideIn 0.3s ease-out;
}
.log-timestamp {
color: #888;
font-size: 0.9em;
margin-bottom: 8px;
}
.log-section {
margin-bottom: 12px;
}
.log-section-title {
color: #667eea;
font-weight: bold;
margin-bottom: 5px;
text-transform: uppercase;
font-size: 0.85em;
}
.log-section-content {
color: #d4d4d4;
padding: 8px;
background: #1e1e1e;
border-radius: 4px;
white-space: pre-wrap;
word-wrap: break-word;
}
.log-json {
color: #ce9178;
}
.log-key {
color: #9cdcfe;
}
.log-string {
color: #ce9178;
}
.log-number {
color: #b5cea8;
}
.messages {
flex: 1;
overflow-y: auto;
padding: 20px;
background: #f8f9fa;
border-radius: 12px;
margin-bottom: 20px;
}
.message {
margin-bottom: 20px;
animation: slideIn 0.3s ease-out;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.message-header {
font-size: 0.9em;
color: #6c757d;
margin-bottom: 5px;
}
.message-content {
padding: 15px;
border-radius: 12px;
line-height: 1.6;
white-space: pre-wrap;
}
.user-message .message-content {
background: #667eea;
color: white;
margin-left: 15%;
}
.bot-message .message-content {
background: white;
color: #212529;
border: 1px solid #e9ecef;
margin-right: 15%;
}
.message-meta {
font-size: 0.85em;
color: #6c757d;
margin-top: 5px;
}
.input-area {
display: flex;
gap: 10px;
}
.input-area input {
flex: 1;
padding: 15px;
border: 2px solid #e9ecef;
border-radius: 12px;
font-size: 1em;
transition: border-color 0.3s;
}
.input-area input:focus {
outline: none;
border-color: #667eea;
}
.input-area button {
padding: 15px 30px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 12px;
font-size: 1em;
cursor: pointer;
transition: transform 0.2s;
}
.input-area button:hover {
transform: scale(1.05);
}
.input-area button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.loading {
display: none;
text-align: center;
padding: 15px;
color: #6c757d;
}
.loading.active {
display: block;
}
.spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 0 auto 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.stats {
padding: 12px;
background: #e7f3ff;
border-radius: 8px;
margin-bottom: 15px;
display: none;
font-size: 0.9em;
}
.stats.active {
display: block;
}
.stat-item {
display: inline-block;
margin-right: 15px;
}
.stat-label {
color: #495057;
font-weight: 500;
}
.stat-value {
color: #667eea;
font-weight: bold;
}
.clear-btn {
padding: 6px 12px;
background: #dc3545;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 0.85em;
float: right;
}
.clear-btn:hover {
background: #c82333;
}
.clear-log-btn {
padding: 8px 16px;
background: #6c757d;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 0.9em;
width: 100%;
margin-top: 10px;
}
.clear-log-btn:hover {
background: #5a6268;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🤖 Bot测试平台</h1>
</div>
<div class="main-content">
<!-- 左侧:人格选择 -->
<div class="sidebar">
<h3>🎭 选择人格</h3>
<ul class="persona-list" id="personaList">
<li class="persona-item active" data-persona="none">
<span class="persona-emoji">🎯</span>
<span>默认(学者)</span>
</li>
<li class="persona-item" data-persona="学者">
<span class="persona-emoji">🎯</span>
<span>学者</span>
</li>
<li class="persona-item" data-persona="逗比">
<span class="persona-emoji">😄</span>
<span>逗比</span>
</li>
<li class="persona-item" data-persona="阴阳">
<span class="persona-emoji">😈</span>
<span>阴阳师</span>
</li>
<li class="persona-item" data-persona="极简">
<span class="persona-emoji">💬</span>
<span>极简</span>
</li>
<li class="persona-item" data-persona="AI模式">
<span class="persona-emoji">🤖</span>
<span>AI模式</span>
</li>
<li class="persona-item" data-persona="文青">
<span class="persona-emoji">🎨</span>
<span>文青</span>
</li>
<li class="persona-item" data-persona="外语">
<span class="persona-emoji">🌍</span>
<span>外国人</span>
</li>
</ul>
<div class="test-mode">
<label>测试场景</label>
<select id="testMode">
<option value="chat">普通对话</option>
<option value="rag">RAG分析</option>
<option value="search">消息搜索</option>
</select>
</div>
<div class="test-mode" style="margin-top: 10px;">
<button class="clear-btn" onclick="clearMessages()">清空对话</button>
</div>
</div>
<!-- 中间:对话区域 -->
<div class="chat-area">
<div class="stats" id="stats">
<div class="stat-item">
<span class="stat-label">响应:</span>
<span class="stat-value" id="responseTime">-</span>
</div>
<div class="stat-item">
<span class="stat-label">消息:</span>
<span class="stat-value" id="messageCount">0</span>
</div>
<div class="stat-item">
<span class="stat-label">人格:</span>
<span class="stat-value" id="currentPersona">默认</span>
</div>
</div>
<div class="messages" id="messages">
<div class="message bot-message">
<div class="message-header">Bot · 系统消息</div>
<div class="message-content">👋 欢迎使用Bot测试平台!
你可以:
· 左侧选择不同的人格模式
· 测试各种查询场景
· 右侧查看完整的Prompt日志
试试问我:
· "谁是最活跃的用户?"
· "最近讨论了什么话题?"
· 或者随便聊聊天 😊</div>
</div>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<div>Bot正在思考中...</div>
</div>
<div class="input-area">
<input
type="text"
id="messageInput"
placeholder="输入测试消息..."
onkeypress="handleKeyPress(event)"
/>
<button onclick="sendMessage()" id="sendBtn">发送</button>
</div>
</div>
<!-- 右侧:Prompt日志 -->
<div class="log-area">
<div class="log-header">
📝 Prompt日志
</div>
<div class="log-content" id="logContent">
<div class="log-entry">
<div class="log-timestamp">等待第一次请求...</div>
<div class="log-section-content">
发送消息后,这里将显示完整的:
· System Prompt
· User Message
· 工具调用信息
· 响应时间统计
</div>
</div>
</div>
<button class="clear-log-btn" onclick="clearLogs()">清空日志</button>
</div>
</div>
</div>
<script>
let selectedPersona = 'none';
let messageCount = 0;
// 人格选择
document.querySelectorAll('.persona-item').forEach(item => {
item.addEventListener('click', function() {
document.querySelectorAll('.persona-item').forEach(i => i.classList.remove('active'));
this.classList.add('active');
selectedPersona = this.dataset.persona;
document.getElementById('currentPersona').textContent =
this.querySelector('span:last-child').textContent;
});
});
// 发送消息
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message) return;
// 构建带人格的消息
let fullMessage = message;
if (selectedPersona !== 'none') {
fullMessage = `@bot ${selectedPersona} ${message}`;
} else {
fullMessage = `@bot ${message}`;
}
// 显示用户消息
addMessage('user', message, selectedPersona);
input.value = '';
// 显示加载状态
document.getElementById('loading').classList.add('active');
document.getElementById('sendBtn').disabled = true;
const startTime = Date.now();
try {
const response = fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: fullMessage,
user: 'test_user'
})
});
const data = response.json();
const endTime = Date.now();
const responseTime = ((endTime - startTime) / 1000).toFixed(2);
// 隐藏加载状态
document.getElementById('loading').classList.remove('active');
document.getElementById('sendBtn').disabled = false;
// 显示Bot响应
addMessage('bot', data.response, null, responseTime);
// 显示Prompt日志
if (data.prompt_info) {
addPromptLog(data.prompt_info, responseTime);
}
// 更新统计
document.getElementById('responseTime').textContent = responseTime + 's';
document.getElementById('stats').classList.add('active');
} catch (error) {
document.getElementById('loading').classList.remove('active');
document.getElementById('sendBtn').disabled = false;
addMessage('bot', '❌ 错误: ' + error.message, null);
}
}
// 添加消息到界面
function addMessage(type, content, persona, responseTime) {
const messagesDiv = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${type}-message`;
const now = new Date().toLocaleTimeString('zh-CN');
const header = type === 'user'
? `测试用户 · ${now}${persona && persona !== 'none' ? ' · ' + persona : ''}`
: `Bot · ${now}`;
let meta = '';
if (responseTime) {
meta = `<div class="message-meta">⏱️ 响应时间: ${responseTime}秒</div>`;
}
messageDiv.innerHTML = `
<div class="message-header">${header}</div>
<div class="message-content">${escapeHtml(content)}</div>
${meta}
`;
messagesDiv.appendChild(messageDiv);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
messageCount++;
document.getElementById('messageCount').textContent = messageCount;
}
// 添加Prompt日志
function addPromptLog(promptInfo, responseTime) {
const logContent = document.getElementById('logContent');
const logEntry = document.createElement('div');
logEntry.className = 'log-entry';
const now = new Date().toLocaleTimeString('zh-CN');
let html = `<div class="log-timestamp">🕐 ${now} (${responseTime}s)</div>`;
// System Prompt
if (promptInfo.system_prompt) {
html += `
<div class="log-section">
<div class="log-section-title">📤 System Prompt (发送给LLM)</div>
<div class="log-section-content">${escapeHtml(promptInfo.system_prompt)}</div>
</div>
`;
}
// User Message
if (promptInfo.user_message) {
html += `
<div class="log-section">
<div class="log-section-title">📤 User Message (发送给LLM)</div>
<div class="log-section-content">${escapeHtml(promptInfo.user_message)}</div>
</div>
`;
}
// 人格信息
if (promptInfo.persona_info) {
html += `
<div class="log-section">
<div class="log-section-title">🎯 人格信息</div>
<div class="log-section-content">${escapeHtml(JSON.stringify(promptInfo.persona_info, null, 2))}</div>
</div>
`;
}
// 工具信息
if (promptInfo.tools) {
html += `
<div class="log-section">
<div class="log-section-title">🔧 可用工具</div>
<div class="log-section-content">${promptInfo.tools.length} 个工具</div>
</div>
`;
}
// 温度和tokens
if (promptInfo.temperature !== undefined) {
html += `
<div class="log-section">
<div class="log-section-title">⚙️ 模型参数</div>
<div class="log-section-content">Temperature: ${promptInfo.temperature}, Max Tokens: ${promptInfo.max_tokens || 1000}</div>
</div>
`;
}
// 执行日志
if (promptInfo.execution_logs && promptInfo.execution_logs.length > 0) {
// 先对每条日志进行HTML转义,然后用<br>连接
const escapedLogs = promptInfo.execution_logs.map(log => escapeHtml(log));
const logsText = escapedLogs.join('<br>');
html += `
<div class="log-section">
<div class="log-section-title">🔍 后端执行日志</div>
<div class="log-section-content">${logsText}</div>
</div>
`;
}
// LLM返回值
if (promptInfo.llm_response) {
const llmResp = promptInfo.llm_response;
const statusIcon = llmResp.success ? '✅' : '❌';
const statusText = llmResp.success ? '成功' : '失败';
const toolCallsText = llmResp.tool_calls ?
'<br><br>工具调用:<br>' + escapeHtml(JSON.stringify(llmResp.tool_calls, null, 2)) : '';
html += `
<div class="log-section">
<div class="log-section-title">📥 LLM返回值</div>
<div class="log-section-content">状态: ${statusIcon} ${statusText}<br>处理时间: ${llmResp.processing_time}<br><br>回复内容:<br>${escapeHtml(llmResp.response_text)}${toolCallsText}</div>
</div>
`;
}
logEntry.innerHTML = html;
logContent.insertBefore(logEntry, logContent.firstChild);
logContent.scrollTop = 0;
}
// HTML转义
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// 按Enter发送
function handleKeyPress(event) {
if (event.key === 'Enter') {
sendMessage();
}
}
// 清空对话
function clearMessages() {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = `
<div class="message bot-message">
<div class="message-header">Bot · 系统消息</div>
<div class="message-content">对话已清空,可以开始新的测试!</div>
</div>
`;
messageCount = 0;
document.getElementById('messageCount').textContent = '0';
document.getElementById('responseTime').textContent = '-';
}
// 清空日志
function clearLogs() {
const logContent = document.getElementById('logContent');
logContent.innerHTML = `
<div class="log-entry">
<div class="log-timestamp">日志已清空</div>
<div class="log-section-content">发送新消息查看Prompt日志...</div>
</div>
`;
}
</script>
</body>
</html>
'''
@app.route('/')
def index():
"""主页"""
return render_template_string(HTML_TEMPLATE)
@app.route('/api/chat', methods=['POST'])
def chat():
"""处理聊天请求,并返回prompt信息"""
try:
data = request.json
message = data.get('message', '')
user = data.get('user', 'test_user')
# 创建日志捕获器
log_capture = LogCapture()
log_capture.setLevel(logging.INFO)
log_capture.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
# 添加到所有相关的logger
loggers_to_capture = [
'chatbot.handlers.ai_interface',
'chatbot.handlers.persona_manager',
'chatbot.analytics.enhanced_rag_analyzer',
'chatbot.analytics.intelligent_query_processor',
'chatbot.analytics.query_templates',
'chatbot.search.semantic_search',
]
for logger_name in loggers_to_capture:
logger = logging.getLogger(logger_name)
logger.addHandler(log_capture)
execution_logs = []
def log_execution(msg):
"""记录执行日志"""
import datetime as dt
timestamp = dt.datetime.now().strftime('%H:%M:%S.%f')[:-3]
execution_logs.append(f"[{timestamp}] {msg}")
log_execution("🚀 开始处理请求")
# 为每个请求创建新的数据库连接(解决SQLite线程安全问题)
log_execution("📦 初始化数据库连接")
thread_message_db = MessageDB(config)
thread_ai_interface = AIInterface(config, openai_client, thread_message_db)
# 获取prompt信息(在调用之前)
log_execution("🎭 检测人格并生成System Prompt")
prompt_info = extract_prompt_info(message, user, thread_ai_interface)
log_execution(f" 检测到人格: {prompt_info.get('persona_info', {}).get('name', '未知')}")
# 调用AI接口处理消息
# 记录开始时间
import time
start_time = time.time()
log_execution("💬 发送请求到AI接口")
result = thread_ai_interface.ai_process_message(message, user)
# 记录结束时间
end_time = time.time()
processing_time = end_time - start_time
log_execution(f"✅ AI处理完成,耗时 {processing_time:.2f}s")
# 检查是否有工具调用
if result.get('tool_calls'):
log_execution(f"🔧 执行了工具调用")
# 获取捕获的日志
captured_logs = log_capture.get_logs()
# 移除日志处理器
for logger_name in loggers_to_capture:
logger = logging.getLogger(logger_name)
logger.removeHandler(log_capture)
# 添加LLM返回信息到prompt_info
prompt_info['llm_response'] = {
'success': result.get('success', False),
'response_text': result.get('response', '处理失败'),
'processing_time': f"{processing_time:.2f}s",
'tool_calls': result.get('tool_calls', None)
}
# 合并执行日志和捕获的日志
all_logs = execution_logs + captured_logs
prompt_info['execution_logs'] = all_logs
log_execution("📤 返回响应给前端")
return jsonify({
'success': result.get('success', False),
'response': result.get('response', '处理失败'),
'prompt_info': prompt_info
})
except Exception as e:
import traceback
error_detail = traceback.format_exc()
print(f"Error in chat endpoint: {error_detail}")
return jsonify({
'success': False,
'response': f'服务器错误: {str(e)}'
}), 500
def extract_prompt_info(message, user, ai_interface_instance):
"""提取prompt相关信息"""
try:
# 检测人格
persona_key, cleaned_message = ai_interface_instance.persona_manager.detect_persona(message)
persona_info = ai_interface_instance.persona_manager.get_persona_info(persona_key)
# 获取system prompt
system_prompt = ai_interface_instance.persona_manager.get_system_prompt(
persona_key, user_id=user
)
# 获取工具列表
tools = ai_interface_instance.tools
# 构建prompt信息
prompt_info = {
'system_prompt': system_prompt,
'user_message': f"用户 '{user}' 通过@你说: '{cleaned_message}'\n请针对这句话回复。",
'persona_info': {
'name': persona_info.get('name'),
'emoji': persona_info.get('emoji'),
'description': persona_info.get('description')
},
'tools': tools,
'temperature': 1.3,
'max_tokens': 1000
}
return prompt_info
except Exception as e:
import traceback
error_detail = traceback.format_exc()
print(f"Error in extract_prompt_info: {error_detail}")
return {
'error': str(e),
'system_prompt': '获取失败',
'user_message': message
}
@app.route('/api/personas', methods=['GET'])
def get_personas():
"""获取可用人格列表"""
personas = [
{'key': 'none', 'name': '默认(学者)', 'emoji': '🎯'},
{'key': '学者', 'name': '学者模式', 'emoji': '🎯'},
{'key': '逗比', 'name': '逗比模式', 'emoji': '😄'},
{'key': '阴阳', 'name': '阴阳师模式', 'emoji': '😈'},
{'key': '极简', 'name': '极简模式', 'emoji': '💬'},
{'key': 'AI模式', 'name': 'AI模式', 'emoji': '🤖'},
{'key': '文青', 'name': '文青模式', 'emoji': '🎨'},
{'key': '外语', 'name': '外国人模式', 'emoji': '🌍'},
]
return jsonify(personas)
if __name__ == '__main__':
print("\n" + "="*60)
print("🚀 Bot测试服务器启动中...")
print("="*60)
print(f"\n📍 访问地址: http://localhost:5050")
print(f"⏰ 启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("\n💡 使用说明:")