-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOnlineInferWindow.cpp
More file actions
416 lines (353 loc) · 11.1 KB
/
OnlineInferWindow.cpp
File metadata and controls
416 lines (353 loc) · 11.1 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
#include "stdafx.h"
#include "OnlineInferWindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonParseError>
#include <QRegularExpression>
#include <QTextCursor>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QTimer>
#include <QPushButton>
#include <QLineEdit>
#include <QTextBrowser>
#include <QScrollBar>
#include <QJSEngine>
#include <QApplication>
OnlineInferWindow::OnlineInferWindow(const QString& url, QWidget* parent)
: QWidget(parent),
manager(new QNetworkAccessManager(this)),
serverUrl(url),
bufferPos(0),
replyFinished(false)
{
// 初始化UI组件
textBrowser = new QTextBrowser(this);
textBrowser->setObjectName("textBrowser");
textBrowser->setReadOnly(true);
textBrowser->setOpenExternalLinks(true);
lineEdit = new QLineEdit(this);
lineEdit->setObjectName("lineEdit");
lineEdit->setPlaceholderText(tr("输入消息..."));
sendButton = new QPushButton(tr("发送"), this);
sendButton->setObjectName("sendButton");
// 布局管理
auto mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(textBrowser);
// 定时器初始化
displayTimer = new QTimer(this);
displayTimer->setInterval(40); // 控制显示速度
// 信号槽连接
connect(sendButton, &QPushButton::clicked, this, &OnlineInferWindow::onSendButtonClicked);
connect(lineEdit, &QLineEdit::returnPressed, sendButton, &QPushButton::click);
connect(displayTimer, &QTimer::timeout, this, &OnlineInferWindow::updateBotReply);
displayTimer->start();
lineEdit->setFocus();
m_newSessionButton = new QPushButton(tr("新会话"), this);
auto inputLayout = new QHBoxLayout();
inputLayout->addWidget(lineEdit);
inputLayout->addWidget(sendButton);
inputLayout->addWidget(m_newSessionButton);
mainLayout->addLayout(inputLayout);
connect(m_newSessionButton, &QPushButton::clicked, this, [=]() {
// 1. 清空聊天显示
textBrowser->clear();
// 2. 清空上下文
chatHistory.clear();
// 3. 清空AI回复缓冲
botReplyBuffer.clear();
bufferPos = 0;
replyFinished = false;
// 4. 停止所有未完成的网络请求
for (auto reply : replyBufferMap.keys()) {
if (reply) {
reply->abort();
reply->deleteLater();
}
}
replyBufferMap.clear();
// 5. 光标回到输入框
lineEdit->setFocus();
});
}
OnlineInferWindow::~OnlineInferWindow()
{
// 清理所有未完成的网络请求
for (auto reply : replyBufferMap.keys()) {
if (reply) {
reply->abort();
reply->deleteLater();
}
}
}
void OnlineInferWindow::onSendButtonClicked()
{
sendButton->setEnabled(false);
const QString text = lineEdit->text().trimmed();
if (text.isEmpty()) return;
// 显示用户输入
textBrowser->append(QString("<b>你:</b> %1").arg(text));
lineEdit->clear();
// 保存用户消息到历史
chatHistory.append({ "user", text });
if (chatHistory.size() > MAX_HISTORY)
chatHistory.removeFirst();
// 重置回复缓冲区
botReplyBuffer.clear();
bufferPos = 0;
replyFinished = false;
// 准备显示AI回复
textBrowser->append("<b>AI:</b> ");
textBrowser->verticalScrollBar()->setValue(textBrowser->verticalScrollBar()->maximum());
// 发送请求时带上下文
sendRequestWithHistory();
}
QString OnlineInferWindow::retrieveKnowledge(const QString& userInput)
{
QFile file(QApplication::applicationDirPath() + QDir::separator() + "data" + QDir::separator() + "knowledge_base.txt");
qDebug() << file.fileName();
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << file.errorString();
return "";
}
QTextStream in(&file);
in.setCodec("UTF-8"); // 强制使用 UTF-8 解码
QString knowledge;
while (!in.atEnd()) {
QString line = in.readLine();
QStringList qTokens = userInput.split(QRegExp("\\W+"), Qt::SkipEmptyParts);
while (!in.atEnd()) {
QString line = in.readLine();
QString lowerLine = line.toLower();
for (const QString& t : qTokens) {
if (t.length() > 1 && lowerLine.contains(t.toLower())) {
knowledge += line + "\n";
break; // 匹配到一个词就够
}
}
}
}
return knowledge.trimmed();
}
bool OnlineInferWindow::isCalculationRequest(const QString& input)
{
return input.contains("+") || input.contains("-") ||
input.contains("*") || input.contains("/");
}
void OnlineInferWindow::sendRequestWithHistory()
{
if (chatHistory.isEmpty()) return;
QString userInput = chatHistory.last().content;
// === RAG: 从本地知识库检索 ===
QString retrieved = retrieveKnowledge(userInput);
if (!retrieved.isEmpty()) {
ChatMessage ragMsg;
ragMsg.role = "system";
ragMsg.content = "参考资料:\n" + retrieved;
chatHistory.append(ragMsg);
qDebug() << "检索本地知识库:" << ragMsg.role << ragMsg.content;
}
// === Agent: 自动计算器工具 ===
if (isCalculationRequest(userInput)) {
QJSEngine engine;
QJSValue value = engine.evaluate(userInput);
if (value.isNumber()) {
double result = value.toNumber();
if (!std::isnan(result) && std::isfinite(result)) {
ChatMessage calcMsg;
calcMsg.role = "system";
calcMsg.content = QString("计算结果: %1").arg(result);
chatHistory.append(calcMsg);
qDebug() << "Agent: 自动计算器工具:" << calcMsg.role << calcMsg.content;
}
}
}
// === 原有发送逻辑 ===
QJsonObject jsonRequest;
QJsonArray messagesArray;
for (const ChatMessage& msg : chatHistory) {
QJsonObject obj;
obj["role"] = msg.role;
obj["content"] = msg.content;
messagesArray.append(obj);
}
jsonRequest["messages"] = messagesArray;
jsonRequest["max_tokens"] = 4096;
QJsonDocument jsonDoc(jsonRequest);
QByteArray requestData = jsonDoc.toJson(QJsonDocument::Compact);
QUrl url(serverUrl);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QNetworkReply* reply = manager->post(request, requestData);
replyBufferMap.insert(reply, QByteArray());
connect(reply, &QNetworkReply::readyRead, this, &OnlineInferWindow::onReplyReadyRead);
connect(reply, &QNetworkReply::finished, this, &OnlineInferWindow::onReplyFinished);
qDebug() << "已发送请求 (长度=" << requestData.size() << ")";
}
void OnlineInferWindow::onReplyReadyRead()
{
auto reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) return;
// 读取并缓存数据
const QByteArray chunk = reply->readAll();
if (!chunk.isEmpty()) {
replyBufferMap[reply].append(chunk);
qDebug() << "接收数据片段 (长度=" << chunk.size() << ") 预览:" << chunk.left(256);
}
}
void OnlineInferWindow::onReplyFinished()
{
auto reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) return;
// 获取完整响应数据
QByteArray fullData = replyBufferMap.take(reply);
if (fullData.isEmpty()) {
fullData = reply->readAll();
}
// 网络错误处理
if (reply->error() != QNetworkReply::NoError) {
textBrowser->append(QString("<span style='color:red;'><b>错误:</b> %1</span>")
.arg(reply->errorString()));
botReplyBuffer = QString("\n[错误详情]\n") + QString::fromUtf8(fullData);
}
else {
// 正常响应处理
QJsonParseError parseError;
QJsonDocument jsonDoc = QJsonDocument::fromJson(fullData, &parseError);
if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
QJsonObject jsonResponse = jsonDoc.object();
QString rawContent;
if (jsonResponse.contains("choices") && jsonResponse["choices"].isArray()) {
QJsonArray choices = jsonResponse["choices"].toArray();
if (!choices.isEmpty()) {
QJsonValue firstChoice = choices.first();
if (firstChoice.isObject()) {
QJsonObject choiceObj = firstChoice.toObject();
if (choiceObj.contains("text")) {
rawContent = choiceObj["text"].toString();
}
else if (choiceObj.contains("message") && choiceObj["message"].isObject()) {
rawContent = choiceObj["message"].toObject()["content"].toString();
}
}
else if (firstChoice.isString()) {
rawContent = firstChoice.toString();
}
if (rawContent.isEmpty()) {
rawContent = QString::fromUtf8(fullData);
}
botReplyBuffer = cleanAIOutput(rawContent);
}
else {
botReplyBuffer = cleanAIOutput(QString::fromUtf8(fullData));
}
}
else {
botReplyBuffer = cleanAIOutput(QString::fromUtf8(fullData));
}
}
else {
qDebug() << "JSON解析错误:" << parseError.errorString();
botReplyBuffer = cleanAIOutput(QString::fromUtf8(fullData));
}
}
// ✅ 保存AI回复到历史上下文
chatHistory.append({ "assistant", botReplyBuffer });
if (chatHistory.size() > MAX_HISTORY)
chatHistory.removeFirst();
replyFinished = true;
reply->deleteLater();
sendButton->setEnabled(true);
}
void OnlineInferWindow::updateBotReply()
{
if (botReplyBuffer.isEmpty() && !replyFinished) return;
// 分段显示回复内容
const int chunkSize = 12;
if (bufferPos < botReplyBuffer.length()) {
const int takeLength = qMin(chunkSize, botReplyBuffer.length() - bufferPos);
const QString piece = botReplyBuffer.mid(bufferPos, takeLength);
bufferPos += takeLength;
textBrowser->moveCursor(QTextCursor::End);
textBrowser->insertPlainText(piece);
textBrowser->moveCursor(QTextCursor::End);
}
// 回复显示完成后重置状态
if (replyFinished && bufferPos >= botReplyBuffer.length()) {
textBrowser->append(""); // 增加空行分隔
botReplyBuffer.clear();
bufferPos = 0;
replyFinished = false;
}
}
QString OnlineInferWindow::cleanAndUnescape(const QString& raw)
{
if (raw.isEmpty()) return {};
QString processed = raw;
// 移除特殊标签
processed.remove(QRegularExpression("<\\|.*?\\|>"));
QString result;
result.reserve(processed.length());
const QChar backslash = '\\';
for (int i = 0; i < processed.length(); ++i) {
QChar current = processed.at(i);
if (current == backslash && i + 1 < processed.length()) {
QChar next = processed.at(i + 1);
switch (next.toLatin1()) {
case 'n': result.append('\n'); i++; break;
case 't': result.append('\t'); i++; break;
case 'r': result.append('\r'); i++; break;
case '\\': result.append('\\'); i++; break;
case '"': result.append('"'); i++; break;
case '\'': result.append('\''); i++; break;
case 'x':
if (i + 3 < processed.length()) {
bool ok = false;
ushort hexVal = processed.mid(i + 2, 2).toUShort(&ok, 16);
if (ok) {
result.append(QChar(hexVal));
i += 3;
break;
}
}
[[fallthrough]];
case 'u':
if (i + 5 < processed.length()) {
bool ok = false;
ushort hexVal = processed.mid(i + 2, 4).toUShort(&ok, 16);
if (ok) {
result.append(QChar(hexVal));
i += 5;
break;
}
}
[[fallthrough]];
default:
result.append(next);
i++;
break;
}
}
else {
result.append(current);
}
}
// 再次清理可能残留的特殊标签
result.remove(QRegularExpression("<\\|.*?\\|>"));
return result;
}
QString OnlineInferWindow::cleanAIOutput(const QString& raw)
{
QString processed = raw;
// 移除Markdown标题
processed.remove(QRegularExpression("^#+\\s.*$", QRegularExpression::MultilineOption));
// 移除末尾多余的反引号
processed.remove(QRegularExpression("`+$"));
// 应用通用清洗规则
return cleanAndUnescape(processed).trimmed();
}