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

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

미스코리아 2년 전 조회 3,170

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

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

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

https://platform.openai.com/account/api-keys">API keys - OpenAI API

 

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

http://mythbot.cafe24.com/">Chatbot Example (cafe24.com)

 

 

</p>

<p><?php

// MySQL 연결 정보

$host = 'localhost';

$username = '00000';

$password = '00000';

$database = '00000';</p>

<p>// ChAtGPt API 키

$apiKey = '00000000000000000000000'; // 실제 API 키로 변경해야 합니다</p>

<p>// ChAtGPt API 엔드포인트

$apiEndpoint = '<a href="https://api.openai.com/v1/chat/completions';" target="_blank" rel="noopener noreferrer">https://api.openai.com/v1/chat/completions';</a></p>

<p>$userInput = $_POST['user_input'];</p>

<p>$mysqli = new mysqli($host, $username, $password, $database);

if ($mysqli->connect_error) {

    die('MySQL 연결에 실패했습니다: ' . $mysqli->connect_error);

}</p>

<p>// ChAtGPt API 호출

$data = array(

    'messages' => array(

        array('role' => 'system', 'content' => 'You are a chatbot'),

        array('role' => 'user', 'content' => $userInput)

    )

);</p>

<p>$options = array(

    'http' => array(

        'header'  => "Content-type: application/json\r\nAuthorization: Bearer $apiKey",

        'method'  => 'POST',

        'content' => json_encode($data)

    )

);</p>

<p>$context  = stream_context_create($options);

$response = file_get_contents($apiEndpoint, false, $context);</p>

<p>if ($response === false) {

    die('ChatGPT API 호출에 실패했습니다.');

}</p>

<p>$responseData = json_decode($response, true);

$chatbotReply = $responseData['choices'][0]['message']['content'];</p>

<p>// 대화 내용 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();</p>

<p>// MySQL 연결 닫기

$mysqli->close();

?></p>

<p><!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></p>

<p>

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

답변 1개

채택된 답변
+20 포인트
A
2년 전

file_get_contents php 설정에서 켜두셨는지 확인해주세요

로그인 후 평가할 수 있습니다

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

답변을 작성하려면 로그인이 필요합니다.

로그인