How to handle deprecated `ChatCompletionRequestMessage` in OpenAI API for the following code?

I’m working on a Next.js application and using OpenAI’s API to handle chat completions. However, I encountered an issue where ChatCompletionRequestMessage seems to be deprecated, and it’s giving me errors. Below is my code:

Client-side Component:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
import { ChatCompletionRequestMessage } from "openai"; // Deprecated?
const CPage = () => {
const router = useRouter();
const [messages, setMessages] = useState<ChatCompletionRequestMessage[]>([]);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
prompt: ""
}
});
const isLoading = form.formState.isSubmitting;
const onSubmit = async (values: z.infer<typeof formSchema>) => {
try {
const userMessage: ChatCompletionRequestMessage = {
role: "user",
content: values.prompt,
};
const newMessages = [...messages, userMessage];
const response = await axios.post("/api/conversation", {
messages: newMessages,
});
setMessages((current) => [...current, userMessage, response.data]);
form.reset();
} catch (error: any) {
console.log(error);
} finally {
router.refresh();
}
};
code ------
<div className="space-y-4 mt-4">
<div className="flex flex-col-reverse gap-y-4">
{messages.map((message) => (
<div key={message.content}>
{message.content}
</div>
))}
more code -----
</code>
<code> import { ChatCompletionRequestMessage } from "openai"; // Deprecated? const CPage = () => { const router = useRouter(); const [messages, setMessages] = useState<ChatCompletionRequestMessage[]>([]); const form = useForm<z.infer<typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues: { prompt: "" } }); const isLoading = form.formState.isSubmitting; const onSubmit = async (values: z.infer<typeof formSchema>) => { try { const userMessage: ChatCompletionRequestMessage = { role: "user", content: values.prompt, }; const newMessages = [...messages, userMessage]; const response = await axios.post("/api/conversation", { messages: newMessages, }); setMessages((current) => [...current, userMessage, response.data]); form.reset(); } catch (error: any) { console.log(error); } finally { router.refresh(); } }; code ------ <div className="space-y-4 mt-4"> <div className="flex flex-col-reverse gap-y-4"> {messages.map((message) => ( <div key={message.content}> {message.content} </div> ))} more code ----- </code>


import { ChatCompletionRequestMessage } from "openai"; // Deprecated?



const CPage = () => {
    const router = useRouter();
    const [messages, setMessages] = useState<ChatCompletionRequestMessage[]>([]);

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            prompt: ""
        }
    });

    const isLoading = form.formState.isSubmitting;

    const onSubmit = async (values: z.infer<typeof formSchema>) => {
        try {
            const userMessage: ChatCompletionRequestMessage = {
                role: "user",
                content: values.prompt,
            };

            const newMessages = [...messages, userMessage];
            const response = await axios.post("/api/conversation", {
                messages: newMessages,
            });
            setMessages((current) => [...current, userMessage, response.data]);

            form.reset();

        } catch (error: any) {
            
            console.log(error);
        } finally {
            router.refresh();
        }
    };

code ------
        
                <div className="space-y-4 mt-4">
                    <div className="flex flex-col-reverse gap-y-4">
                        {messages.map((message) => (
                            <div key={message.content}>
                                {message.content}
                            </div>
                        ))}
more code -----

API Route:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(req: Request) {
try {
const { userId } = auth();
const body = await req.json();
const { messages } = body;
if (!userId) {
return new NextResponse("Unauthorized", { status: 401 });
}
if (!openai.apiKey) {
return new NextResponse("Open AI API Key not configured", { status: 500 });
}
if (!messages) {
return new NextResponse("Messages are required", { status: 400 });
}
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages,
});
return NextResponse.json(response.choices[0].message);
} catch (error) {
console.log("[CONVERSATION_ERROR]", error);
return new NextResponse("Internal error", { status: 500 });
}
}
</code>
<code>import { auth } from '@clerk/nextjs/server'; import { NextResponse } from 'next/server'; import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); export async function POST(req: Request) { try { const { userId } = auth(); const body = await req.json(); const { messages } = body; if (!userId) { return new NextResponse("Unauthorized", { status: 401 }); } if (!openai.apiKey) { return new NextResponse("Open AI API Key not configured", { status: 500 }); } if (!messages) { return new NextResponse("Messages are required", { status: 400 }); } const response = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages, }); return NextResponse.json(response.choices[0].message); } catch (error) { console.log("[CONVERSATION_ERROR]", error); return new NextResponse("Internal error", { status: 500 }); } } </code>
import { auth } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';
import OpenAI from 'openai';

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

export async function POST(req: Request) {
    try {
        const { userId } = auth();
        const body = await req.json();
        const { messages } = body;

        if (!userId) {
            return new NextResponse("Unauthorized", { status: 401 });
        }

        if (!openai.apiKey) {
            return new NextResponse("Open AI API Key not configured", { status: 500 });
        }

        if (!messages) {
            return new NextResponse("Messages are required", { status: 400 });
        }

        const response = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages,
        });

        return NextResponse.json(response.choices[0].message);

    } catch (error) {
        console.log("[CONVERSATION_ERROR]", error);
        return new NextResponse("Internal error", { status: 500 });
    }
}

I want to use the OpenAI Node.js SDK version 4, but I am encountering issues with ChatCompletionRequestMessage being deprecated. How should I update my code to use the correct types and methods in version 4?

Any help would be greatly appreciated. Thank you in advance!


Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật