본문 바로가기
DEVEL/PHP

PHP ChatGPT API 예제

by codebyai 2023. 7. 20.
반응형

curl 사용 코드

<?php
    // Your OpenAI API key
    $api_key = 'your-api-key';

    $data_string = json_encode([
        'prompt' => 'Translate this sentence into French: "{text}"',
        'max_tokens' => 60
    ]);

    $ch = curl_init('https://api.openai.com/v1/engines/davinci-codex/completions');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'Content-Length: ' . strlen($data_string)
    ));

    $result = curl_exec($ch);
    $response = json_decode($result, true);

    // print result
    echo $response['choices'][0]['text'];
?>

 

GuzzleHttp 사용 코드

<?php
    require 'vendor/autoload.php';
    use GuzzleHttp\Client;

    // Your OpenAI API key
    $api_key = 'your-api-key';

    $data = [
        'prompt' => 'Translate this sentence into French: "{text}"',
        'max_tokens' => 60
    ];

    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'https://api.openai.com',
        // You can set any number of default request options.
        'timeout'  => 2.0,
    ]);

    $response = $client->request('POST', '/v1/engines/davinci-codex/completions', [
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ],
        'json' => $data
    ]);

    $body = $response->getBody();
    $arr_body = json_decode($body, true);

    echo $arr_body['choices'][0]['text'];
?>

 

max_tokens => 60은 결과로 반환될 토큰의 최대 수를 지정

 

davinci-codex/completions는 OpenAI의 GPT-3엔진에 대한 요청을 보내는 엔드포인트로 GPT-4 또는 다른 엔진을 사용하려면 해당 엔진의 엔드포인트를 사용해야 한다.

 

API키는 OpenAI의 웹사이트(https://platform.openai.com/account/api-keys)에서 발급할 수 있다.

 

 

VPN 이상의 가치, 노드VPN! 10주년 역대급 69%할인!

 

김보성의 차고 : 신차 장기 렌터카/리스 가격비교 플랫폼

 

매일매일 새로운 이성과 톡하는 빠른 매칭 채팅 앱, '데이톡'

 

한국을 좋아하는 외국인 이성친구 만드는 "케이메이트"

 

 

반응형