2023년 4월 19일

php 로 챗GPT api 사용방법. 라이브러리 그딴거 없이 누구나 쉽게

진짜 최고로 간단하게 만들어 봤습니다.

나의 php소스코드 윗부분에 다음의 함수를 붙여넣는다.  API키만 내가 받은걸로 넣기.


function fnGPTComment($memo) {  
    $api_key = '나의 API키';
    $url = "https://api.openai.com/v1/completions";

    // "What is the capital of France?"
    $prompt = filter_var($memo, FILTER_SANITIZE_STRING);

    $data = array(
        "model" => "text-davinci-003",  
        "prompt" => $prompt,
        "max_tokens" => 3000,
        "temperature" => 0.5,
    );

    $data_string = json_encode($data);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "Authorization: Bearer $api_key",
        "Content-Length: " . strlen($data_string))
    );

    $output = curl_exec($ch);
    curl_close($ch);

    $output_json = json_decode($output, true);
    return $output_json["choices"][0]["text"];
}


그리고 GPT의 대답을 듣고 싶은부분에서 함수를 호출


$prompt = 'GPT한테 하고싶은말을 주저리주저리 쓰고';
$comment_memo = fnGPTComment( $prompt );
echo $comment_memo; // GPT 가 보내온 문장을 화면에 보여줌


댓글 없음:

댓글 쓰기

추천 게시물

시놀로지 NAS 외부 접속이 안될떄 점검 항목(최종본)

 1. DNS 서버 주소 확인   ☞ DSM의 제어판>네트워크>일반  수동으로 DNS 서버 구성      기본 DNS는 8.8.8.8  대체 DNS는 8.8.4.4 로 설정한다. 2. LAN 포트를 2개 이상 사용할 경우 기본 게이트웨이 확...