How to connect php with swoole to ChatGPT interface

The following steps are required to connect to the ChatGPT interface:

  1. Install the Swoole extension and the PHP cURL extension.

  2. Introduce in the project composer require guzzlehttp/guzzleto install the Guzzle HTTP client.

  3. Write the HTTP request code to call the ChatGPT interface, the sample code is as follows:

$client = new \GuzzleHttp\Client();
$res = $client->request('POST', 'https://api.openai.com/v1/engines/davinci-codex/completions', [
    'headers' => [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer ' . $your_api_key,
    ],
    'json' => [
        'prompt' => 'Hello,',
        'temperature' => 0.5,
        'max_tokens' => 60,
        'n' => 1,
        'stop' => '.',
    ],
]);

if ($res->getStatusCode() == 200) {
    
    
    $response = json_decode($res->getBody(), true);
    echo $response['choices'][0]['text'];
}

In this sample code, we use the Guzzle HTTP client library to send HTTP requests. The header of the request includes the content type (Content-Type) and your API key. The request body includes the specified prompt (prompt) and other parameters such as temperature (temperature), maximum number of tokens (max tokens) and stop tokens (stop tokens). We can use the returned response to get the generated text.

  1. Integrate the above code into the Swoole project to trigger an HTTP request for ChatGPT to generate text and send the response back to the client.

The sample code is as follows:

$server = new Swoole\HTTP\Server("127.0.0.1", 9501);

$server->on("request", function ($req, $res) {
    
    
    $client = new \GuzzleHttp\Client();

    $res = $client->request('POST', 'https://api.openai.com/v1/engines/davinci-codex/completions', [
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $your_api_key,
        ],
        'json' => [
            'prompt' => 'Hello,',
            'temperature' => 0.5,
            'max_tokens' => 60,
            'n' => 1,
            'stop' => '.',
        ],
    ]);

    if ($res->getStatusCode() == 200) {
    
    
        $response = json_decode($res->getBody(), true);
        $generated_text = $response['choices'][0]['text'];
        $res->end($generated_text);
    } else {
    
    
        $res->end("Error: " . $res->getStatusCode());
    }
});

$server->start();

In this sample code, we created a Swoole HTTP server and sent the HTTP request in the "request" event handler. We get the generated text from the response and send the text back to the client. If the request fails, an error message is sent to the client.

The above are the steps of using Swoole and ChatGPT interface integration in PHP.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131155975