通过后端代理聊天接口,可以在响应数据前处理一些业务逻辑,例如用户身份校验,或用户提交数据的一些前置处理,以下是guzzle客户端的简单demo实现:

<?php
require './vendor/autoload.php';

ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

ignore_user_abort(true);

$client = new GuzzleHttp\Client();

$json = json_decode(file_get_contents("php://input"), true);

try{
    $response = $client->request('POST', 'https://api.openai.com/v1/chat/completions', [
        'stream'=>true,
        'json' => json_decode($json, true),
        'headers' => [
            'Authorization' => 'Bearer ' . $YOUR_API_KEY,
            'Accept'        => 'application/json',
        ]
        'timeout' => 120,
        'connect_timeout' => 120,
    ]);

    //$body is now a Guzzle stream object.
    $body = $response->getBody();

    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: *");
    header("Access-Control-Allow-Origin: *");
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');

    $fullContent = null;

    while(!$body->eof()) {
        if (connection_aborted()) {
            break;
        }
        $chunk = $body->read(8192);
        echo $chunk;
        echo PHP_EOL;
        if (ob_get_level() > 0) {
            ob_flush();
        }
        flush();

        $explode = explode("data:", $chunk);
        foreach($explode as $jsonString){
            $jsonArray = json_decode($jsonString, true);
            if($json && isset($jsonArray['choices'][0]['delta']['content'])){       
                if(!$fullContent){
                    $fullContent = $jsonArray;
                }else{
                    $fullContent['choices'][0]['delta']['content'] .= $jsonArray['choices'][0]['delta']['content'];
                }
            }
        }
    }
    // $fullContent contains full response json content from openai
}catch (\GuzzleHttp\Exception\ClientException $e){
    // your exception code, var_dump($e->getResponse()->getBody()->getContents()); // Body, normally it is JSON;
}catch (\GuzzleHttp\Exception\GuzzleException $e){
    // your exception code, var_dump($e->getMessage());
}catch (\Exception $e){
    // your exception code
    // var_dump($e->getMessage());
    // var_dump($e->getTraceAsString());
}

如果您觉得您在我这里学到了新姿势,博主支持转载,姿势本身就是用来相互学习的。同时,本站文章如未注明均为 hisune 原创 请尊重劳动成果 转载请注明 转自: 使用guzzle代理chatgpt聊天API接口 - hisune.com