NextJS 13 API接口500错误:TypeError读取headers属性失败
问题解决步骤
1. 修正配置变量拼写错误
代码里的configutation是拼写错误,正确应为configuration。错误的变量名会导致OpenAI客户端初始化失败,后续调用API时因缺少有效配置,出现headers未定义的报错。
修改后的配置代码:
const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration);
2. 替换GPT-4的API调用方法
GPT-4不支持createCompletion接口(该接口仅适用于GPT-3系列模型),需改用createChatCompletion接口,同时调整参数格式为聊天消息数组:
修改try块内的代码:
const aiResult = await openai.createChatCompletion({ model: "gpt-4", messages: [{ role: "user", content: prompt }], temperature: 0.9, max_tokens: 8192, }); const aiText = aiResult.data.choices[0].message?.content?.trim() || "Something went wrong!";
3. 完善错误处理逻辑
原代码的catch块未返回响应,导致请求无返回值触发500错误,需在catch中返回明确的错误响应:
修改后的catch块:
catch (error: any) { console.error(error); return NextResponse.json( { error: error.message || "Failed to generate response" }, { status: 500 } ); }
4. 验证环境变量
确保.env.local文件中已正确设置OPENAI_API_KEY,并且重启开发服务器让环境变量生效:
OPENAI_API_KEY=your-openai-api-key-here
完整修正后的代码
import { NextResponse } from "next/server"; import { Configuration, OpenAIApi } from "openai"; const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); export async function POST(request: Request) { const body = await request.json(); const { prompt } = body; if (!prompt || prompt === "") { return new Response("Please send your prompt", { status: 400 }); } try { const aiResult = await openai.createChatCompletion({ model: "gpt-4", messages: [{ role: "user", content: prompt }], temperature: 0.9, max_tokens: 8192, }); const aiText = aiResult.data.choices[0].message?.content?.trim() || "Something went wrong!"; return NextResponse.json({ text: aiText }); } catch (error: any) { console.error(error); return NextResponse.json( { error: error.message || "Failed to generate response" }, { status: 500 } ); } }
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

