This commit is contained in:
zhuzihcu 2023-03-17 14:29:13 +08:00
parent 28b65e2f33
commit 6b54401371
3 changed files with 17 additions and 17 deletions

View File

@ -65,7 +65,7 @@
# 部分效果预览
## 内置一个ChatGPT聊天Demo
## 一个聊天Demo调用了ChatGPT的接口
![](doc/preview/chatgpt.png)

View File

@ -12,7 +12,7 @@ void ChatController::sendMessage(const QString& text){
QUrl apiUrl("https://api.openai.com/v1/engines/text-davinci-003/completions");
QNetworkRequest request(apiUrl);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Authorization", "Bearer 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");
request.setRawHeader("Authorization", QString::fromStdString("Bearer %1").arg(QString::fromUtf8(QByteArray::fromBase64(baseKey.toUtf8()))).toUtf8());
QJsonObject requestData;
requestData.insert("prompt", text);
requestData.insert("max_tokens", 1000);
@ -21,21 +21,20 @@ void ChatController::sendMessage(const QString& text){
QByteArray requestDataBytes = requestDoc.toJson();
QNetworkReply* reply = networkManager->post(request, requestDataBytes);
connect(reply, &QNetworkReply::finished,this, [=]() {
QString responseString = QString::fromUtf8(reply->readAll());
qDebug() << responseString;
QJsonDocument doc = QJsonDocument::fromJson(responseString.toUtf8());
QJsonObject jsonObj = doc.object();
QString text = jsonObj.value("choices").toArray().at(0).toObject().value("text").toString();
if(text.isEmpty()){
text = "不好意思,我似乎听不懂您的意思";
if (reply->error() == QNetworkReply::NoError) {
QString responseString = QString::fromUtf8(reply->readAll());
qDebug() << responseString;
QJsonDocument doc = QJsonDocument::fromJson(responseString.toUtf8());
QJsonObject jsonObj = doc.object();
QString text = jsonObj.value("choices").toArray().at(0).toObject().value("text").toString();
if(text.isEmpty()){
text = "不好意思,我似乎听不懂您的意思";
}
responseData(text);
reply->deleteLater();
isLoading(false);
} else {
responseData("网络错误:"+reply->errorString());
}
responseData(text);
reply->deleteLater();
isLoading(false);
});
connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::errorOccurred), this, [=](QNetworkReply::NetworkError) {
qDebug() << "Network error occurred: " << reply->errorString();
reply->deleteLater();
isLoading(false);
});
}

View File

@ -22,6 +22,7 @@ public:
private:
QNetworkAccessManager* networkManager;
QString baseKey = "c2stbXgxWm5MQkZ5TzhNYzNmRWl6eDZUM0JsYmtGSnNBWjNiakJjSXB6WGN3QW9KSk11";
};
#endif // CHATCONTROLLER_H