ChatGPT API与jQuery调用异常:响应截断且不符合指令
问题分析与修复方案
核心问题原因
1. 内容分析被截断
你的chatgpt_api.php中固定设置了max_tokens: 100,而GPT-3.5-turbo的token与中文的换算比例约为1token≈0.75个汉字,100token仅能生成约75字的内容,这直接导致首次内容分析被截断。
2. 生成文章不符合要求
- 你传递给生成文章接口的是截断后的不完整分析结果,模型无法基于残缺信息生成符合要求的完整文章;
- 生成文章时依然沿用
max_tokens: 100的限制,即使prompt逻辑正确,也只能生成极短的片段内容。
修复步骤与代码调整
1. 修改PHP接口的token限制与错误处理
根据场景动态设置max_tokens值,同时完善API调用的错误捕获逻辑:
<?php $api_key = 'XXXX'; if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['prompt'])) { $prompt = $_POST['prompt']; // 根据prompt类型分配token额度:内容分析用500,生成文章用1500(适配1000字左右的输出) $maxTokens = strpos($prompt, '撰写内容分析') !== false ? 500 : 1500; $data = [ 'model' => 'gpt-3.5-turbo', 'messages' => [['role' => 'user', 'content' => $prompt]], 'max_tokens' => $maxTokens, 'temperature' => 0.7 // 控制生成内容的随机性,可选调整 ]; $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)); curl_setopt($ch, CURLOPT_FAILONERROR, true); // 捕获HTTP错误 $response = curl_exec($ch); $curlError = curl_error($ch); curl_close($ch); // 处理curl调用错误 if ($curlError) { echo 'API调用失败: ' . $curlError; exit; } $responseData = json_decode($response, true); // 处理OpenAI返回的业务错误 if (isset($responseData['error'])) { echo 'OpenAI错误提示: ' . $responseData['error']['message']; exit; } $message = $responseData['choices'][0]['message']['content'] ?? '未获取到有效响应'; echo $message; } ?>
2. 优化前端JS的参数传递与错误处理
确保错误提示指向对应内容容器,同时优化prompt的中文表述:
function fetchChatGPTResponse(content, postNo) { $.ajax({ url: 'chatgpt_api.php', method: 'POST', data: { prompt: '基于以下内容撰写内容分析:' + content }, success: function(response) { const targetDiv = document.getElementById('response' + postNo); targetDiv.innerHTML = response + `<br><button onclick="fetchChatGPTArticle('${encodeURIComponent(response)}', '${postNo}');">撰写内容</button>`; }, error: function() { document.getElementById('response' + postNo).innerText = "请求失败,请重试"; } }); } function fetchChatGPTArticle(analysis, postNo) { $.ajax({ url: 'chatgpt_api.php', method: 'POST', data: { prompt: '基于以下内容分析,撰写一篇1000字左右的文章,内容需有吸引力,不得包含点赞、评论相关数据:' + decodeURIComponent(analysis) }, success: function(article) { document.getElementById('article' + postNo).innerHTML = article; }, error: function() { document.getElementById('article' + postNo).innerText = "请求失败,请重试"; } }); }
额外注意事项
max_tokens的总上限不能超过模型限制(GPT-3.5-turbo为4096token),需预留prompt本身占用的token空间;- 如果原始输入
content过长,需先做截断处理,避免总token数超出模型上限; - 可在前端添加加载状态提示,提升用户体验。
内容的提问来源于stack exchange,提问作者BCLtd
相关产品推荐
相关产品推荐

