The problem with slow connection to OpenAI API in PHP [closed]

I have written a code to connect to OpenAI API in PHP, which performs the following tasks:
It takes an Excel file as input and connects to ChatGPT for each of the titles in that Excel file, receiving responses. Then, it puts all the responses in an Excel file.

Now I have a questions:

The speed of this connection and receiving responses from OpenAI is very slow, to the point where the server becomes unavailable. How can I increase the speed?

function connect_ai($question,$topic){
    $ch = curl_init();
    $url="https://api.openai.com/v1/chat/completions";
    $api_key = 'sk-';
    if(!empty($question)){      
        $post_fields = array(
            "model" => "gpt-3.5-turbo",
            "messages" => array(
                array(
                    "role" => "user",
                    "content" => $question . " " . $topic
                )
            ),
            "max_tokens" => 950,
            "temperature" => 0
        );
        $header  = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $api_key
        ];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_fields));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error: ' . curl_error($ch);
        }
        $response = json_decode($result);
        //print_r($response);
    }

    return $response;
}

Leave a Comment