我正在尝试将 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/