我有一些用于分析内容的JavaScript代码,它首先生成内容分析,然后添加一个“编写内容”的按钮,用于根据内容分析编写内容。
我的问题是第一部分的分析可以正常工作,但它只生成大约前50个词左右就中断了。当我点击“编写内容”按钮时,它似乎是生成接下来的50个词,而不是根据提示进行实际操作。
我哪里做错了?我的API调用是否正确?
<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) { // 在响应div中显示内容分析 document.getElementById('response' + postNo).innerHTML = response + `<br><button onclick="fetchChatGPTArticle('${encodeURIComponent(response)}', '${postNo}');">编写内容</button>`; }, error: function() { document.getElementById('response').innerText = "错误"; } }); } function fetchChatGPTArticle(article, postNo2) { $.ajax({ url: 'chatgpt_api.php', method: 'POST', data: { prompt: '基于此内容分析,请编写一篇1000字的文章来加强这个声明,确保文章引人入胜。不要包含任何关于点赞和评论的统计数据:' + decodeURIComponent(article) }, success: function(article) { // 在文章div中显示生成的文章 document.getElementById('article' + postNo2).innerHTML = article; }, error: function() { document.getElementById('article' + postNo2).innerText = "错误"; } }); } </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}?>
回答:
你提到的大约50个词的问题是有道理的,删除API调用主体中的’max_tokens’限制器,你应该就能解决这个问题
$data = [ 'model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => $prompt]],];