diff --git a/README.md b/README.md index 28f02e0..0bb167c 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ # 部分效果预览 -## 内置一个ChatGPT聊天Demo +## 一个聊天Demo,调用了ChatGPT的接口 ![](doc/preview/chatgpt.png) diff --git a/example/ChatController.cpp b/example/ChatController.cpp index 2e728cd..ec22e00 100644 --- a/example/ChatController.cpp +++ b/example/ChatController.cpp @@ -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::of(&QNetworkReply::errorOccurred), this, [=](QNetworkReply::NetworkError) { - qDebug() << "Network error occurred: " << reply->errorString(); - reply->deleteLater(); - isLoading(false); }); } diff --git a/example/ChatController.h b/example/ChatController.h index acfa73c..30d23a5 100644 --- a/example/ChatController.h +++ b/example/ChatController.h @@ -22,6 +22,7 @@ public: private: QNetworkAccessManager* networkManager; + QString baseKey = "c2stbXgxWm5MQkZ5TzhNYzNmRWl6eDZUM0JsYmtGSnNBWjNiakJjSXB6WGN3QW9KSk11"; }; #endif // CHATCONTROLLER_H