You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAI v4.8.0在NextJS中调用Chat.Completions.create报错求助

问题排查与解决

核心原因

OpenAI v4.x版本相较于v3.x,API调用方式发生了重大变化:必须使用实例对象调用方法,而非直接通过类调用。你当前代码中直接用OpenAI.Chat.Completions.create是v3的写法,v4不再支持这种方式。

修正步骤

  • 使用你创建的实例(而非OpenAI类)来调用方法
  • 修正参数拼写错误:message需改为messages
  • 将字符串格式的prompt包装为符合要求的消息对象

修正后的代码

import OpenAI from "openai";

const instructionMessage = {
    role: "system",
    content: "Some instructions",
};

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY,
});

const prompt = "Prompt";
const temperature = 0.7;
const response = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [instructionMessage, { role: "user", content: prompt }],
        temperature,
        max_tokens: 1000,
    });

补充说明

  • v4版本中API方法采用小驼峰命名(chat.completions.create而非Chat.Completions.create)
  • messages参数必须是包含消息对象的数组,每个对象必须有role和content字段

内容的提问来源于stack exchange,提问作者Korovjov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 17:52:14