React项目调用GPT API返回空字符串问题排查求助
问题排查与修复方案
1. 核心错误:Prompt使用未定义变量
代码里的prompt模板字符串用了${text},但存储用户输入的状态变量是textScript,导致发送给API的prompt缺少待判断的文本内容,API无法生成有效响应。
修复代码:
const prompt = `Answer with only 'Yes' or 'No'. Is the following text about soccer? ${textScript}`;
明确要求模型仅返回Yes/No,同时清晰传入用户输入的文本,让模型明确任务目标。
2. 状态变量与更新函数命名不规范(非致命但影响可读性)
状态初始化时的更新函数命名不符合React驼峰规范,建议修正:
const [textScript, setTextScript] = useState("");
(注:你的textarea onChange事件里已经正确使用了setTextScript,此处是初始化时的笔误,规范命名可避免后续混淆)
3. 结果渲染逻辑错误
JSX中的判断条件错用了未定义的isTextScript,实际存储API结果的状态是isTextScriptAPI,且显示文本逻辑混乱,建议修改为:
{isTextScriptAPI !== "" && ( <h3>判断结果:{isTextScriptAPI}</h3> )}
或者更直观的表述:
{isTextScriptAPI !== "" && ( <h3>这段文本{isTextScriptAPI === 'Yes' ? '是' : '不是'}关于足球的内容</h3> )}
4. 可选优化:调整API参数提升准确性
- 将
max_tokens设为10即可,因为仅需要Yes/No的简短结果 - 进一步明确prompt指令,避免模型返回多余内容
修复后的callOpenAIAPI函数示例:
async function callOpenAIAPI() { console.log("Calling API"); const prompt = `Answer with only 'Yes' or 'No'. Is the following text about soccer? ${textScript}`; const APIBody = { model: "text-davinci-003", prompt, temperature: 0, max_tokens: 10, top_p: 1, frequency_penalty: 0.0, presence_penalty: 0.0, stop: ["\n"] }; try { const response = await fetch("https://api.openai.com/v1/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${API_KEY}` }, body: JSON.stringify(APIBody) }); const data = await response.json(); console.log(data); if (data.choices && data.choices.length > 0) { const generatedText = data.choices[0].text.trim(); setIsTextScriptAPI(generatedText); } else { setIsTextScriptAPI("No response from the API"); } } catch (error) { console.error("Error:", error); setIsTextScriptAPI("API call failed"); } }
内容的提问来源于stack exchange,提问作者APMOO101
相关产品推荐
相关产品推荐

