chat-gpt api 적용중 "ChatGPT API 호출에 실패했습니다."

chat-gpt api 적용중 "ChatGPT API 호출에 실패했습니다."

QA

chat-gpt api 적용중 "ChatGPT API 호출에 실패했습니다."

본문

chat-gpt api 적용해서 php 만들어봤는데 에러가 발생합니다.

"ChatGPT API 호출에 실패했습니다."

php 파일레 API키 정상적으로 발급받아서 입력했는데요

API keys - OpenAI API

 

어디가 문제인지 알 수 있을까요?

Chatbot Example (cafe24.com)

 

 


<?php
// MySQL 연결 정보
$host = 'localhost';
$username = '00000';
$password = '00000';
$database = '00000';
// ChAtGPt API 키
$apiKey = '00000000000000000000000'; // 실제 API 키로 변경해야 합니다
// ChAtGPt API 엔드포인트
$apiEndpoint = 'https://api.openai.com/v1/chat/completions';
$userInput = $_POST['user_input'];
$mysqli = new mysqli($host, $username, $password, $database);
if ($mysqli->connect_error) {
    die('MySQL 연결에 실패했습니다: ' . $mysqli->connect_error);
}
// ChAtGPt API 호출
$data = array(
    'messages' => array(
        array('role' => 'system', 'content' => 'You are a chatbot'),
        array('role' => 'user', 'content' => $userInput)
    )
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\nAuthorization: Bearer $apiKey",
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);
$context  = stream_context_create($options);
$response = file_get_contents($apiEndpoint, false, $context);
if ($response === false) {
    die('ChatGPT API 호출에 실패했습니다.');
}
$responseData = json_decode($response, true);
$chatbotReply = $responseData['choices'][0]['message']['content'];
// 대화 내용 MySQL에 저장
$query = "INSERT INTO chat_history (user_input, chatbot_reply) VALUES (?, ?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $userInput, $chatbotReply);
$stmt->execute();
$stmt->close();
// MySQL 연결 닫기
$mysqli->close();
?>
<!DOCTYPE html>
<html>
<head>
    <title>Chatbot Example - 결과</title>
</head>
<body>
    <h1>Chatbot Example - 결과</h1>
    <p><strong>사용자 입력:</strong> <?php echo $userInput; ?></p>
    <p><strong>챗봇 응답:</strong> <?php echo $chatbotReply; ?></p>
</body>
</html>

이 질문에 댓글 쓰기 :

답변 1

답변을 작성하시기 전에 로그인 해주세요.
전체 46
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT