Page 1 of 1

gemini post returns response 200, but the result is empty

Posted: Tue Feb 04, 2025 3:19 pm
by vigyanabikshu
I am trying to get response from gemini. post returns response 200, but the result is empty!. ca_certificate problem ?


// Send HTTP POST request to the Gemini API
void send_gemini_request(void) {
char question[200] = "What is Todays Significance?";
ESP_LOGI(TAG, "Asking Your Question: %s", question);

esp_http_client_config_t config = {
.url = "https://generativelanguage.googleapis.c ... ntent?key=" GEMINI_API_KEY,
.method = HTTP_METHOD_POST,
.cert_pem = postman_root_cert_pem_start, // Add server certificate if required
.buffer_size = 2048, // Increase buffer size if needed
.disable_auto_redirect = false,
.keep_alive_enable = true,
.user_agent = "ESP32",
};

ESP_LOGI(TAG, "URL: %s", config.url);
esp_http_client_handle_t client = esp_http_client_init(&config);

// Prepare the payload
// char payload[512];
const char *payload = "{"
"\"contents\": [{"
"\"parts\": [{"
"\"text\": \"What is Todays Significance?\""
"}]"
"}],"
"\"generationConfig\": {"
"\"maxOutputTokens\": 800"
"}"
"}";
//snprintf(payload, sizeof(payload), "{\"contents\": [{\"parts\":[{\"text\":%s}]}],\"generationConfig\": {\"maxOutputTokens\": %s}}", question, GEMINI_MAX_TOKENS);
ESP_LOGI(TAG, "Payload: %s", payload);

// Set headers
esp_http_client_set_header(client, "Content-Type", "application/json");
esp_http_client_set_header(client, "Authorization", GEMINI_API_KEY);
esp_http_client_set_method(client, HTTP_METHOD_POST);

// Send the request
esp_http_client_set_post_field(client, payload, strlen(payload));
esp_err_t err = esp_http_client_perform(client);
if (err == ESP_OK) {
int status_code = esp_http_client_get_status_code(client);
ESP_LOGI(TAG, "Status Code: %d", status_code);
if (status_code == 200) {
long contentlength = esp_http_client_get_content_length(client);
ESP_LOGI(TAG, "Received Content Length: %ld", contentlength);
if(contentlength>0){
char* response = malloc(contentlength + 1);
esp_http_client_read(client, response, esp_http_client_get_content_length(client));
response[esp_http_client_get_content_length(client)] = '\0';
}
ESP_LOGI(TAG, "response: %s", payload);
} else {
ESP_LOGE(TAG, "HTTP request failed with status code: %d", status_code);
}
} else {
ESP_LOGE(TAG, "HTTP request failed: %s", esp_err_to_name(err));
}

esp_http_client_cleanup(client);
}



I (12184) mbedtls: ssl_msg.c:4206 <= read record

I (12194) mbedtls: ssl_msg.c:5867 <= read

I (12204) GEMINI_EXAMPLE: Status Code: 200
I (12204) GEMINI_EXAMPLE: Received Content Length: -1
I (12214) GEMINI_EXAMPLE: response: {"contents": [{"parts": [{"text": "What is Todays Significance?"}]}],"generationConfig": {"maxOutputTokens": 800}}

Re: gemini post returns response 200, but the result is empty

Posted: Tue Feb 04, 2025 6:10 pm
by MicroController
esp_http_client_get_content_length()
Returns:
(-1) Chunked transfer

Re: gemini post returns response 200, but the result is empty

Posted: Fri Feb 07, 2025 1:29 am
by vigyanabikshu
In Arduino, the below code works fine and get result from gemini

if (https.begin("https://generativelanguage.googleapis.c ... ntent?key=" + (String)Gemini_Token)) { // HTTPS

https.addHeader("Content-Type", "application/json");
String payload = String("{\"contents\": [{\"parts\":[{\"text\":" + res + "}]}],\"generationConfig\": {\"maxOutputTokens\": " + (String)Gemini_Max_Tokens + "}}");

Serial.println("Payload: " +payload);

//Serial.print("[HTTPS] GET...\n");

// start connection and send HTTP header
int httpCode = https.POST(payload);

Serial.println(httpCode);

// httpCode will be negative on error
// file found at server

if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = https.getString();
//Serial.println(payload);

DynamicJsonDocument doc(4096);


deserializeJson(doc, payload);
String Answer = doc["candidates"][0]["content"]["parts"][0]["text"];



// For Filtering our Special Characters, WhiteSpaces and NewLine Characters
Answer.trim();
String filteredAnswer = "";
for (size_t i = 0; i < Answer.length(); i++) {
char c = Answer;
if (isalnum(c) || isspace(c)) {
filteredAnswer += c;
} else {
filteredAnswer += ' ';
}
}
Answer = filteredAnswer;

int answerLength = Answer.length();
int filteredAnswerLength = filteredAnswer.length();

Serial.println("Answer length: " + String(answerLength));
Serial.println("Filtered answer length: " + String(filteredAnswerLength));


Serial.println("");
Serial.println("Here is your Answer: ");
Serial.println("");
Serial.println(Answer);
} else {
Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
}
https.end();
} else {
Serial.printf("[HTTPS] Unable to connect\n");
}

Re: gemini post returns response 200, but the result is empty

Posted: Fri Feb 07, 2025 8:28 am
by MicroController
The point is that esp_http_client_get_content_length() can return -1 (when the server uses chunked transfer to send the data), and you cannot rely on esp_http_client_get_content_length() returning > 0, i.e. the content length being known in advance.

Re: gemini post returns response 200, but the result is empty

Posted: Fri Feb 07, 2025 2:23 pm
by vigyanabikshu
MicroController wrote:
Fri Feb 07, 2025 8:28 am
The point is that esp_http_client_get_content_length() can return -1 (when the server uses chunked transfer to send the data), and you cannot rely on esp_http_client_get_content_length() returning > 0, i.e. the content length being known in advance.
Thanks for your kind reply. I tried receiving chunked data, but still nothing receiving

if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to perform HTTP request");
cJSON_Delete(root);
esp_http_client_cleanup(client);
return err;
}else{
char buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
int total_read = 0;
int read_len;

// Read response in chunks
do {
read_len = esp_http_client_read(client, buffer, MAX_HTTP_OUTPUT_BUFFER - 1);
if (read_len > 0) {
buffer[read_len] = '\0'; // Null-terminate for safe logging
total_read += read_len;
ESP_LOGI(TAG, "%s", buffer); // Print chunk
}
} while (read_len > 0);

ESP_LOGI(TAG, "Total Response Size: %d bytes", total_read);

Re: gemini post returns response 200, but the result is empty

Posted: Fri Feb 07, 2025 3:25 pm
by markdh102
Change your
while (read_len > 0)
to
while (total_read == 0 || read_len > 0)

Also be worth adding a timeout clause in the do loop to exit after 5s for example if nothing has been received.