Skip to content

Commit d8a96c5

Browse files
Ryan Detzelryanrdetzel
authored andcommitted
fix(openai): Fix chunked data failing when making a request
1 parent 6a112f4 commit d8a96c5

File tree

1 file changed

+40
-11
lines changed

1 file changed

+40
-11
lines changed

components/openai/OpenAI.c

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2395,20 +2395,49 @@ static char *OpenAI_Request(const char *base_url, const char *api_key, const cha
23952395
OPENAI_ERROR_CHECK_GOTO(wlen >= 0, "Failed to write client!", end);
23962396
}
23972397
int content_length = esp_http_client_fetch_headers(client);
2398-
if (esp_http_client_is_chunked_response(client)) {
2399-
esp_http_client_get_chunk_length(client, &content_length);
2398+
ESP_LOGI(TAG, "content_length=%d", content_length);
2399+
2400+
int buffer_size = (content_length > 0) ? content_length : 4096;
2401+
int total_read = 0;
2402+
result = malloc(buffer_size);
2403+
OPENAI_ERROR_CHECK_GOTO(result != NULL, "Failed to allocate memory", end);
2404+
2405+
while (1)
2406+
{
2407+
int read_len = esp_http_client_read_response(client, result + total_read, buffer_size - total_read);
2408+
if (read_len <= 0)
2409+
break;
2410+
total_read += read_len;
2411+
2412+
if (total_read >= buffer_size - 1)
2413+
{
2414+
ESP_LOGD(TAG, "Buffer size exceeded, reallocating memory");
2415+
buffer_size *= 2;
2416+
char *new_buffer = realloc(result, buffer_size);
2417+
if (new_buffer == NULL)
2418+
{
2419+
ESP_LOGE(TAG, "Failed to allocate memory");
2420+
free(result);
2421+
result = NULL;
2422+
goto end;
2423+
}
2424+
result = new_buffer;
2425+
}
2426+
2427+
if (esp_http_client_is_complete_data_received(client))
2428+
break;
24002429
}
2401-
ESP_LOGD(TAG, "content_length=%d", content_length);
2402-
OPENAI_ERROR_CHECK_GOTO(content_length > 0, "HTTP client fetch headers failed!", end);
2403-
result = (char *)malloc(content_length + 1);
2404-
int read = esp_http_client_read_response(client, result, content_length);
2405-
if (read != content_length) {
2406-
ESP_LOGE(TAG, "HTTP_ERROR: read=%d, length=%d", read, content_length);
2430+
2431+
if (total_read > 0)
2432+
{
2433+
result[total_read] = '\0';
2434+
ESP_LOGD(TAG, "result: %s, size: %d", result, total_read);
2435+
}
2436+
else
2437+
{
24072438
free(result);
24082439
result = NULL;
2409-
} else {
2410-
result[content_length] = 0;
2411-
ESP_LOGD(TAG, "result: %s, size: %d", result, strlen(result));
2440+
ESP_LOGE(TAG, "No data received");
24122441
}
24132442

24142443
end:

0 commit comments

Comments
 (0)