FluentUI/example/ChatController.cpp

57 lines
2.1 KiB
C++
Raw Permalink Normal View History

2023-03-17 14:05:27 +08:00
#include "ChatController.h"
ChatController::ChatController(QObject *parent)
: QObject{parent}
{
isLoading(false);
networkManager = new QNetworkAccessManager(this);
}
2023-03-17 17:56:50 +08:00
2023-03-17 14:05:27 +08:00
void ChatController::sendMessage(const QString& text){
isLoading(true);
2023-03-17 17:56:50 +08:00
QUrl apiUrl("https://api.openai.com/v1/chat/completions");
2023-03-17 14:05:27 +08:00
QNetworkRequest request(apiUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
2023-03-17 14:29:13 +08:00
request.setRawHeader("Authorization", QString::fromStdString("Bearer %1").arg(QString::fromUtf8(QByteArray::fromBase64(baseKey.toUtf8()))).toUtf8());
2023-03-17 14:05:27 +08:00
QJsonObject requestData;
2023-03-17 17:56:50 +08:00
requestData.insert("model", "gpt-3.5-turbo");
messages.append(createMessage("user",text));
requestData.insert("messages", messages);
2023-03-17 14:05:27 +08:00
QJsonDocument requestDoc(requestData);
QByteArray requestDataBytes = requestDoc.toJson();
QNetworkReply* reply = networkManager->post(request, requestDataBytes);
connect(reply, &QNetworkReply::finished,this, [=]() {
2023-03-17 14:29:13 +08:00
if (reply->error() == QNetworkReply::NoError) {
QString responseString = QString::fromUtf8(reply->readAll());
qDebug() << responseString;
QJsonDocument doc = QJsonDocument::fromJson(responseString.toUtf8());
QJsonObject jsonObj = doc.object();
2023-03-17 17:56:50 +08:00
QString text = jsonObj.value("choices").toArray().at(0).toObject().value("message").toObject().value("content").toString();
2023-03-17 14:29:13 +08:00
if(text.isEmpty()){
2023-03-17 23:01:48 +08:00
text = "响应错误content为空数据";
2023-03-17 17:56:50 +08:00
}else{
messages.append(createMessage("assistant",text));
2023-03-17 14:29:13 +08:00
}
2023-03-17 17:56:50 +08:00
responseData(text.trimmed());
2023-03-17 14:29:13 +08:00
} else {
responseData("网络错误:"+reply->errorString());
2023-03-17 14:05:27 +08:00
}
2023-03-17 14:33:46 +08:00
isLoading(false);
reply->deleteLater();
2023-03-17 14:05:27 +08:00
});
}
2023-03-17 17:56:50 +08:00
QJsonObject ChatController::createMessage(const QString& role,const QString& content){
2023-03-18 22:52:24 +08:00
QJsonObject message;
message.insert("role",role);
message.insert("content",content);
return message;
2023-03-17 17:56:50 +08:00
}
2023-03-18 20:20:59 +08:00
void ChatController::clipText(const QString& text){
qDebug()<<text;
2023-03-18 22:52:24 +08:00
QClipboard *clipboard = QGuiApplication::clipboard();
clipboard->setText(text);
2023-03-18 20:20:59 +08:00
}