테스트 사이트 - 개발 중인 베타 버전입니다

[PHP] OpenAI API 호출

· 7개월 전 · 363 · 1

31463534_1742957901.3594.jpg

 

 

 

 

 

 

 




[광고] 여러분의 추억을 공유해 주세요! - https://김타자.kr

 

 

 

 

 

 

 

 

 

 

 

function callOpenAI($messages) {
    
    $api_key = "sk-"; //OpenAI API 키 입력
    $model = "gpt-3.5-turbo";
    
    // OpenAI API URL
    $url = "https://api.openai.com/v1/chat/completions";

    // 요청 데이터 배열 생성
    $data = array(
        "model" => $model,
        "messages" => array(
            array("role" => "user", "content" => $messages)
        ),
        "temperature" => 0.7,
        "max_tokens" => 500
    );

    // JSON 변환
    $data_json = json_encode($data);

    // cURL 초기화
    $ch = curl_init();

    // cURL 옵션 설정
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json",
        "Authorization: Bearer " . $api_key
    ));

    // API 호출 및 응답 저장
    $response = curl_exec($ch);

    // 오류 체크
    if (curl_errno($ch)) {
        return "cURL Error: " . curl_error($ch);
    }

    // cURL 닫기
    curl_close($ch);

    // JSON 디코딩하여 반환    
    return json_decode($response, true);
    
}

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

댓글 1개

7개월 전

팁게인가 게시판중에 리자님이 올려놓은 실용 소스도 있습니다. 

게시글 목록

번호 제목
712
711
709
702
698
696
695
680
679
673
672
662
655
649
641
640
634
615
607
605
603
591
588
584
583
579
578
564
559
557