Malformed http response Dalle3

I am having issues with image generation. This is the error I am getting in my console:

Sending request to OpenAI API:
Endpoint: https://api.openai.com/v1/images/generations
Headers:
Authorization: Bearer REDACTED
Content-Type: application/json
Request Body: {
    "model": "dall-e-3",
    "n": 1,
    "prompt": "create an image of a cat playing with a ball of yarn.",
    "size": "1024x1024"
}
[Tue May 14 15:14:51 2024] ERROR: HTTP(S) error on https connection to api.openai.com:443: Malformed HTTP response
Received response from OpenAI API:
Status: 0
Body:
Error from OpenAI API. Status: 0. Body:
[Tue May 14 15:14:51 2024] ERROR: Error from OpenAI API. Status: 0. Body:

And this is the code that I am using:

        else if (sub_command == "image") {
            std::string prompt = std::get<std::string>(event.get_parameter("prompt"));

            // OpenAI DALL-E 3 API setup
            const std::string endpoint = "https://api.openai.com/v1/images/generations";
            const std::string api_key = DatabaseManager::getInstance().getOpenAIApiKey();

            nlohmann::json request_body = {
                {"model", "dall-e-3"},
                {"prompt", prompt},
                {"n", 1},
                {"size", "1024x1024"}
            };

            std::multimap<std::string, std::string> headers = {
                {"Authorization", "Bearer " + api_key},
                {"Content-Type", "application/json"}
            };

            // Log the request details
            std::cout << "Sending request to OpenAI API:" << std::endl;
            std::cout << "Endpoint: " << endpoint << std::endl;
            std::cout << "Headers: " << std::endl;
            for (const auto& header : headers) {
                std::cout << header.first << ": " << header.second << std::endl;
            }
            std::cout << "Request Body: " << request_body.dump(4) << std::endl;

            event.thinking();

            bot.request(endpoint, dpp::http_method::m_post,
                [event, &bot](const dpp::http_request_completion_t& response) {
                    // Log the response details
                    std::cout << "Received response from OpenAI API:" << std::endl;
                    std::cout << "Status: " << response.status << std::endl;
                    std::cout << "Body: " << response.body << std::endl;

                    if (response.status == 200) {
                        nlohmann::json response_json = nlohmann::json::parse(response.body);

                        std::cout << "Image Generation Response: " << response_json.dump(4) << std::endl;

                        // Log the response to a file
                        std::ofstream log_file("openai_response.log", std::ios::app);
                        if (log_file.is_open()) {
                            log_file << "Image Generation Response:\n" << response_json.dump(4) << "\n\n";
                            log_file.close();
                        }
                        else {
                            std::cerr << "Failed to open log file." << std::endl;
                        }

                        std::string image_url = response_json["data"][0]["url"].get<std::string>();

                        event.edit_original_response(dpp::message(image_url));
                    }
                    else {
                        std::string error_message = "Error from OpenAI API. Status: " + std::to_string(response.status) + ". Body: " + response.body;
                        std::cerr << error_message << std::endl;

                        // Log the error details
                        bot.log(dpp::ll_error, error_message);

                        event.edit_original_response(dpp::message("An error occurred while processing your request."));
                    }
                },
                request_body.dump(), "application/json", headers, "1.0"
            );
        }

When looking at my usage in the API it seems as if the post is going through because the API is showing image generations. However it seems that something gets lost in translation and I get that malformed response. Any help would be greatly appreciated.

A few suggestions:

  • Did you check your rate limit on your api?
  • Have you set the correct permissions on your api key?
  • Have you tested this with a curl to see what happens?
    ** for example:
curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "dall-e-3",
    "prompt": "a white siamese cat",
    "n": 1,
    "size": "1024x1024"
  }'

A few suggestions:

  • have you verified the dpp library can send and receive to other endpoints?
  • have you retrieved the latest version with new ciphers and brotli decompression?
  • have you considered tossing libraries for Discord bots out the window?

I had an AI refactor for you, not seeing the rest of your code to know what else might be going on or really being any kind of ace programmer myself:



To use libcurl in your code, you’ll need to include the libcurl headers and link the library. Make sure you have libcurl installed on your system. Here’s the modified code using libcurl:

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <curl/curl.h>

// Include nlohmann::json header
#include <nlohmann/json.hpp>

// ...

else if (sub_command == "image") {
    std::string prompt = std::get<std::string>(event.get_parameter("prompt"));

    // OpenAI DALL-E 3 API setup
    const std::string endpoint = "https://api.openai.com/v1/images/generations";
    const std::string api_key = DatabaseManager::getInstance().getOpenAIApiKey();

    nlohmann::json request_body = {
        {"model", "dall-e-3"},
        {"prompt", prompt},
        {"n", 1},
        {"size", "1024x1024"}
    };

    std::string request_body_str = request_body.dump();

    // Log the request details
    std::cout << "Sending request to OpenAI API:" << std::endl;
    std::cout << "Endpoint: " << endpoint << std::endl;
    std::cout << "Request Body: " << request_body_str << std::endl;

    event.thinking();

    // Initialize libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    CURL* curl = curl_easy_init();

    if (curl) {
        // Set up libcurl options
        curl_easy_setopt(curl, CURLOPT_URL, endpoint.c_str());
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_body_str.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request_body_str.length());

        // Set up headers
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // Set up response handling
        std::string response_str;
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, [](void* contents, size_t size, size_t nmemb, void* userp) {
            ((std::string*)userp)->append((char*)contents, size * nmemb);
            return size * nmemb;
        });
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_str);

        // Perform the request
        CURLcode res = curl_easy_perform(curl);

        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        } else {
            long response_code;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);

            // Log the response details
            std::cout << "Received response from OpenAI API:" << std::endl;
            std::cout << "Status: " << response_code << std::endl;
            std::cout << "Body: " << response_str << std::endl;

            if (response_code == 200) {
                nlohmann::json response_json = nlohmann::json::parse(response_str);

                std::cout << "Image Generation Response: " << response_json.dump(4) << std::endl;

                // Log the response to a file
                std::ofstream log_file("openai_response.log", std::ios::app);
                if (log_file.is_open()) {
                    log_file << "Image Generation Response:\n" << response_json.dump(4) << "\n\n";
                    log_file.close();
                }
                else {
                    std::cerr << "Failed to open log file." << std::endl;
                }

                std::string image_url = response_json["data"][0]["url"].get<std::string>();

                event.edit_original_response(dpp::message(image_url));
            }
            else {
                std::string error_message = "Error from OpenAI API. Status: " + std::to_string(response_code) + ". Body: " + response_str;
                std::cerr << error_message << std::endl;

                // Log the error details
                bot.log(dpp::ll_error, error_message);

                event.edit_original_response(dpp::message("An error occurred while processing your request."));
            }
        }

        // Clean up
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }

    curl_global_cleanup();
}

This code initializes libcurl, sets up the necessary options, and performs the request. The response is then parsed and processed as in the original code. Make sure to link the libcurl library when compiling your code.

testing it via curl on a linux box works just fine.