基于谷歌模型gemini-pro 的开发的QT 对话项目

发布时间:2023年12月24日

支持的功能,新建对话框,目前发现相关梯子不支持访问谷歌的api 的可能代理设置的不对,

 QNetworkAccessManager manager;

    // Set up your request
    QNetworkRequest request;
    request.setUrl(QUrl("https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=AIz****n_XRciLfpdkgruY"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // Set up your JSON data
    QJsonObject textObj1;
    textObj1["text"] = "写一个故事";

    QJsonObject userRole1;
    userRole1["role"] = "user";
    userRole1["parts"] = QJsonArray() << textObj1;

    QJsonObject textObj2;
    textObj2["text"] = "In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind.";

    QJsonObject modelRole;
    modelRole["role"] = "model";
    modelRole["parts"] = QJsonArray() << textObj2;

    QJsonObject textObj3;
    textObj3["text"] = "你用中文写一个故事?";

    QJsonObject userRole2;
    userRole2["role"] = "user";
    userRole2["parts"] = QJsonArray() << textObj3;

    QJsonArray contents;
    contents << userRole1 << modelRole << userRole2;

    QJsonObject mainObj;
    mainObj["contents"] = contents;

    QJsonDocument doc(mainObj);

    // Send the POST request
    QNetworkReply *reply = manager.post(request, doc.toJson());

    // Create an event loop
    QEventLoop loop;
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));

    // Wait until 'finished()' is emitted
    loop.exec();

    // Check the reply
    if (reply->error() == QNetworkReply::NoError) {
        QString strReply = (QString)reply->readAll();

        // Parse the JSON response
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());
        QJsonObject jsonObject = jsonResponse.object();
        QJsonArray candidatesArray = jsonObject["candidates"].toArray();

        // Assume we only want the first candidate
        if (!candidatesArray.isEmpty()) {
            QJsonObject firstCandidate = candidatesArray[0].toObject();
            QJsonObject contentObject = firstCandidate["content"].toObject();
            QJsonArray partsArray = contentObject["parts"].toArray();

            // Assume we only want the text of the first part
            if (!partsArray.isEmpty()) {
                QJsonObject firstPart = partsArray[0].toObject();
                QString text = firstPart["text"].toString();

                qDebug() << "Extracted text: " << text;
            }
        }
    }
    else {
        qDebug() << "Failure" <<reply->errorString();
    }
    delete reply;

重点是QT的SSL :根据QT 的版本下载相关的ssl库

void MainWindow::provideContextMenu(const QPoint &pos) {
    QPoint globalPos = ui->listWidget->mapToGlobal(pos);

    QMenu menu;
    QAction *copyAction = menu.addAction("Copy");
    QAction *selectedItem = menu.exec(globalPos);

    if (selectedItem == copyAction) {
        QList<QListWidgetItem *> items = ui->listWidget->selectedItems();
        QStringList text;
        foreach(QListWidgetItem *item, items) {
            text.append(item->text());
        }
        QApplication::clipboard()->setText(text.join("\n"));
    }
}
void MainWindow::initializeChatSaveFile() {
    // 确保存储目录存在
      QString storeDirectory = "store";
      QDir dir(storeDirectory);
      if (!dir.exists()) {
          dir.mkpath("."); // 如果不存在,则创建目录
      }

      // 获取目录下所有的 txt 文件
      QStringList chatFiles = dir.entryList(QStringList() << "chat_*.txt", QDir::Files, QDir::Name);

      if (!chatFiles.isEmpty()) {
          // 如果至少存在一个文件,则读取第一个文件
          currentChatFileName = storeDirectory + "/" + chatFiles.first();
      } else {
          // 如果不存在任何文件,则创建一个新文件
          currentChatFileName = storeDirectory + "/chat_1.txt";
          QFile file(currentChatFileName);
          file.open(QIODevice::WriteOnly); // 创建新文件
          file.close();
      }
}

void MainWindow::saveChatAutomatically() {
    QFile file(currentChatFileName);
        if (!file.open(QIODevice::Append | QIODevice::Text)) {
            // 如果文件不能被打开,显示一个错误消息框
            QMessageBox::information(this, tr("Unable to open file"), file.errorString());
            return;
        }

        QTextStream out(&file);
        for (int i = 0; i < ui->listWidget->count(); ++i) {
            QListWidgetItem *item = ui->listWidget->item(i);
            out << item->text() << "\n"; // 写入每一行文本及一个换行符
        }

        file.close(); // 关闭文件
}
void MainWindow::showContextMenu(const QPoint &pos) {
    QPoint globalPos = ui->listView->mapToGlobal(pos);
       QMenu menu;

       QModelIndex index = ui->listView->indexAt(pos);
       if (index.isValid()) {
           // 如果点击的是有效项,则显示删除选项
           QAction *deleteAction = menu.addAction("删除对话");
           connect(deleteAction, &QAction::triggered, this, &MainWindow::deleteSelectedItem);
       } else {
           // 如果点击的是空白区域,则显示新建选项
           QAction *newAction = menu.addAction("添加新的对话");
           connect(newAction, &QAction::triggered, this, &MainWindow::createNewFile);
       }

       menu.exec(globalPos);
}

void MainWindow::deleteSelectedItem() {
    QModelIndex index = ui->listView->currentIndex();
    if (index.isValid()) {
        // 删除模型中的项
        model->removeRow(index.row());

        // 可选: 删除对应的文件
        QString fileName = model->itemFromIndex(index)->text();
        QFile::remove("store/" + fileName);
    }
}
void MainWindow::createNewFile() {
    // 获取下一个文件编号
       int fileNumber = 1;
       QString fileName;
       do {
           fileName = QString("store/chat_%1.txt").arg(fileNumber++);
       } while (QFile::exists(fileName));

       QFile file(fileName);
       if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
           // 错误处理,无法创建文件
           qDebug() << "Unable to create the file:" << fileName;
           return;
       }
       file.close();

       // 更新当前聊天文件名
       currentChatFileName = fileName;

       // 添加新项到ListView
       QStandardItem *item = new QStandardItem(QFileInfo(file).fileName());
       model->appendRow(item);

       // 选中并滚动到新创建的文件
       QModelIndex index = model->indexFromItem(item);
       ui->listView->setCurrentIndex(index);
       ui->listView->scrollTo(index);

       // 清空或加载新文件的内容到 QListWidget
       loadChatContent(); // 假设这个函数会清空当前内容并加载新文件的内容
}
void MainWindow::onFileDoubleClicked(const QModelIndex &index) {
    if (!index.isValid()) return;

    QString fileName = model->itemFromIndex(index)->text();
    currentChatFileName = "store/" + fileName; // 更新当前聊天文件名
    loadChatContent(); // 加载对应的聊天内容
}

?完整版本代码,评论区留言邮箱发给你们(免费)

后续也会上传到github 上进行开源

想要获取直接运行版本的也可以直接留言私信我。

文章来源:https://blog.csdn.net/weixin_43608857/article/details/135183545
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。