I have some javascript that is analysing content, it generates a content analysis of content initially, and then adds a button to "write content" about the content analysis.
My problem is the first section to analyse works, but it only generates the first 50 words or so and cuts off. When I click the write content button, it seems to generate the next 50 words and not actually do according to the prompt.
What am I doing wrong? is my API calls correct?
<script>
function fetchChatGPTResponse(content, postNo) {
$.ajax({
url: 'chatgpt_api.php',
method: 'POST',
data: {
prompt: 'write a content analysis based on this: ' + content // Use the post content as the prompt
},
success: function(response) {
// Display the content analysis in the response div
document.getElementById('response' + postNo).innerHTML = response + `<br><button onclick="fetchChatGPTArticle('${encodeURIComponent(response)}', '${postNo}');">Write Content</button>`;
},
error: function() {
document.getElementById('response').innerText = "Error";
}
});
}
function fetchChatGPTArticle(article, postNo2) {
$.ajax({
url: 'chatgpt_api.php',
method: 'POST',
data: {
prompt: 'Based on this content analysis pasted after this statement, could you write me an article to reinforce this statement in 1000 words, ensure that it is engaging. Don\'t include any stats about upvotes and comments: ' + decodeURIComponent(article)
},
success: function(article) {
// Display the generated article in the article div
document.getElementById('article' + postNo2).innerHTML = article;
},
error: function() {
document.getElementById('article' + postNo2).innerText = "Error";
}
});
}
</script>
chatgpt_api.php:
<?php
$api_key = 'XXXX';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['prompt'])) {
$prompt = $_POST['prompt'];
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => $prompt]],
'max_tokens' => 100
];
$headers = [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);
$message = $responseData['choices'][0]['message']['content'] ?? 'No response from ChatGPT.';
echo $message; // Return the response to the AJAX call
}
?>
Your noting of about 50 words make sense, remove the 'max_tokens' limiter in the body of your API call and you should be good
$data = [
'model' => 'gpt-3.5-turbo',
'messages' => [['role' => 'user', 'content' => $prompt]],
];