php - ChatGPT OpenAI 与 API 中的问题

标签 php openai-api chatgpt-api

我正在尝试将 ChatGPT (OpenAI) 集成到我的网站中,以便它可以回答用户问题。但是,我遇到了 ChatGPT 不提供任何响应的问题。我在下面提供了相关的代码片段。我也收到了API key 并替换了它,但它仍然只返回null。

index.php:

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT Example</title>
</head>
<body>
    <h1>Chat with ChatGPT</h1>

    <div id="chat-container">
        <div id="chat-history">
            <!-- Chat messages will be displayed here -->
        </div>
        <div id="user-input">
            <input type="text" id="user-message" placeholder="Type your message..." />
            <button onclick="sendMessage()">Send</button>
        </div>
    </div>

    <script>
        async function sendMessage() {
            const userMessage = document.getElementById('user-message').value;
            if (userMessage.trim() === '') return;

            appendMessage('You', userMessage);

            const response = await fetch('get_response.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message: userMessage }),
            });

            const responseData = await response.json();
            const chatGptResponse = responseData.response;
            appendMessage('ChatGPT', chatGptResponse);
        }

        function appendMessage(sender, message) {
            const chatHistory = document.getElementById('chat-history');
            const messageDiv = document.createElement('div');
            messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
            chatHistory.appendChild(messageDiv);

            // Scroll to the bottom of the chat history
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }
    </script>
</body>
</html>

get_response.php:

<?php
// Include your OpenAI API key
$apiKey = 'YOUR_OPENAI_API_KEY';

// Get the user's message from the request
$userMessage = $_POST['message'];

// Make a request to the OpenAI API
$apiUrl = 'https://api.openai.com/v1/chat/completions';
$data = [
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => $userMessage],
    ],
];
$options = [
    'http' => [
        'header' => "Content-Type: application/json\r\nAuthorization: Bearer $apiKey",
        'method' => 'POST',
        'content' => json_encode($data),
    ],
];
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
$decodedResponse = json_decode($response, true);

// Get the assistant's reply
$assistantReply = $decodedResponse['choices'][0]['message']['content'];

// Return the response
header('Content-Type: application/json');
echo json_encode(['response' => $assistantReply]);
?>

最佳答案

您应该在数据中包含 ChatGPT 模型之一才能使其发挥作用。我刚刚修改了您的 $data 以使用 GPT-3.5-Turbo 模型,如下所示。

$data = [
 'messages' => [
    ['role' => 'system', 'content' => 'You are a helpful assistant.'],
    ['role' => 'user', 'content' => $userMessage],
  ],
  "model" => "gpt-3.5-turbo",
];

关于php - ChatGPT OpenAI 与 API 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76843774/

相关文章:

token - 聊天GPT : How to use long texts of unknown content in a prompt?

PHP 和 Num_Of_Rows() 函数的使用?

openai-api - 如何使用 OpenAI 的 gpt-3.5-turbo API 防止幻觉?

google-colaboratory - 在 Google Colab 中运行 AutoGPT。 Chrome 无法访问

openai-api - 如何计算整个ChatGPT对话的token?

sas - ChatGPT API 在 SAS 中集成时出错。无效的上下文类型 header

php - 在 WooCommerce 订单编辑页面中按 “menu order” 对订单项目进行排序

javascript - Yii 客户端脚本在一行中注册脚本

php - MySQL JOIN 在 PHP 中为多个 HTML 表排列结果

android - 如何在 OpenAi Kotlin Client 中使用编辑图像